Why is my Typescript code not functioning properly even after including the reference path?

I recently created two files:

main.ts:

///<reference path="./external.ts"/>

welcome();

external.ts

var welcome = function() {
    console.log("hi there");
}

After compiling both files to JavaScript and running them using the command: $ node main.js

I was surprised when the 'welcome' function didn't execute as expected. Instead, I encountered an error:

ReferenceError: welcome is not defined

Upon researching about triple-slash directive (https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html), it was mentioned that:

The compiler does a preprocessing pass on input files to resolve all triple-slash reference directives. This process includes adding additional files to compilation.

Despite this explanation, I still struggle to comprehend why the function from external.ts file couldn't be accessed.

Answer №1

If you are working in a Node environment, the approach mentioned above won't work as-is. You'll need to import (require) the file in order to use it with Node.

Here's what you need to do:

// external.js
export var hello = function() {
    console.log("hello");
}

And then use it like this:

// main.js

const { hello } = require("./external");

hello();

Additionally, when compiling your code, make sure to compile it for Node by using:

tsc -m commonjs ./main.ts

Answer №2

The main purpose of a reference file is to describe the various functions, types, and interfaces available in a program without diving into their implementation details.

It focuses more on declaration rather than implementation, providing guidance for the compiler to understand the structure of the code.

For example, if we take a look at a simple scenario in a file named main.ts, where the following code snippet is present:

console.log('hi')

Without the required @types/node package, the compilation process would fail as the compiler wouldn't recognize the 'console' object. This is why having reference files becomes crucial:

- By including reference files, we are essentially informing the compiler that there exists a 'console' object with a 'log' method.

In practice, you can create a declaration in a file like hello.d.ts:

declare function hello(): void;  

and then refer to it in your hello.ts file:

/// <reference path="./hello.d.ts" />

hello();  

As a result, when you compile the code using tsc hello.ts, the compiler successfully recognizes 'hello' as a function that can be invoked.

Nevertheless, running the script through node hello.js may lead to a ReferenceError since, technically speaking, the 'hello()' function is not implemented by the node engine during runtime.

One way to see this in action is by trying something like:

console.log('hello') 

This statement will execute correctly because it's an engine-provided function, aiding in better comprehension of the concept.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Export all the interfaces that have been imported

I have created an NPM package that includes a class with multiple interfaces defined in a "types.ts" file. However, I am encountering an issue where I am unable to access these interfaces when attempting to use the package myself. It seems that I may need ...

Throw an error of Type - TypeError when the provided prop is beyond the permissible range

I am working on a component that accepts two props - children (React elements) and index. The purpose of this component is to return the child element at a specific index when the index is passed in. However, I want to enhance my types to throw a type er ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

Typescript's Array extension causes issues with constructors

During my experimentation with TypeScript, I encountered an interesting behavior: class ExtArray<U> extends Array<U> { constructor(...args : U[]) { super(...args); } public contains(element : U) : boolean { var i ...

Introducing a new element in TypeScript using a separate method with parameters

Currently, I am attempting to create a method that will allow me to add an element to my array. Despite being new to typescript, I have been struggling to determine what needs to go into the addNewProduct function. While seeking help, I came across the p ...

What is the best way to implement type discrimination in TypeScript?

When using TypeScript with two interfaces combined as a union type, why doesn't it distinguish which type members can be declared? interface IFish { swim: () => void; } interface ICat { meow: () => void; } type Pet = IFish | ICat; const p ...

The functionality of NgbModal in ng-bootstrap is experiencing issues and becoming unresponsive in ng-bootstrap version 15 and Angular version 16

Currently, I am in the process of upgrading my Angular app from version 15 to version 16. Following the documentation, I have updated the @ng-bootstrap/ng-bootstrap package to version 15. However, after this update, I am facing issues with the NgbModals no ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...

How can I set up TypeScript warnings in Visual Studio Code to display as errors?

Take this scenario for instance async function a() { await null; } In VS Code, there is a minor warning about using await: 'await' has no effect on the type of this expression. ts(80007) Is there a way to elevate that warning to an error in b ...

Accessing embedded component within an Angular template

I have a ng-template that I utilize to generate a modal with a form on top of one of my other components like this: <div> <h1>Main component content...</h1> <button (click)="modals.show(newthingmodal)">Create New T ...

Comparing SomeType to SomeType[] - Which One Is Better?

Using a constant string value to narrow down a union type is simple and effective: type Payload1 = { /* ... arbitrary type ... */ }; type Payload2 = { /* ... arbitrary type ... */ }; type T1 = { type: 'type1', payload: Payload1 } type T2 = { type ...

Having trouble getting web components registered when testing Lit Element (lit-element) with @web/test-runner and @open-wc/testing-helpers?

Currently, I am working with Lit Element and Typescript for my project. Here are the dependencies for my tests: "@esm-bundle/chai": "^4.3.4-fix.0", "@open-wc/chai-dom-equals": "^0.12.36", "@open-wc/testing-help ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

No response was forthcoming

I have been trying to send a post request to my login endpoint, but I am not receiving any response. Despite thoroughly checking my code, I am unable to figure out why there is no response being sent back. My backend is built using Express in TypeScript. B ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

The IDE is showing an error, but Jest is able to run it flawlessly

I recently created a Jest unit test for a TypeScript function called checkEmail, which internally uses showAlert. The showAlert function in the utils.ts file looks like this: export const showAlert = (message: string) => { toast(message); }; In my ...

typescript What is the best approach to searching within a nested array?

I am struggling to extract a specific value from a nested array within an array. Here is an example structure of my array: [ { ConcessionId: 1, ConcessionName: "Coyotes", KnownAs: [ { TeamId: 1, ...

Error: The <Class> cannot be accessed until it has been initialized

I have a basic autoloader method that initializes and returns an instance of a class using require() The require statement includes some logic that requests information from a database and checks if the class exists in the filesystem. let elementClass = r ...

Error encountered while attempting to globally install TypeScript using npm: "npm ERR! code -13"

Issue with npm error 13 Having trouble installing typescript-g package Error details: - errno: -13, - npm ERR! code: 'EACCES', - npm ERR! syscall: 'symlink', - npm ERR! path: '../lib/node_modules/typescript/bin/tsc', ...