If we add a JS file in the typescript project, we will encounter errors. In this JS file, we can't use any typescript features, so we can't annotate parameters of functions. If we import our JS file into the TS file, we get a compile error because by default JS code is not included in the compilation process. To solve this problem we have to go to tsconfig code, in the Javascript support section, we have to turn on “allowJs”: true
/* JavaScript Support */
"allowJs": true,
Type checking JS code
By using JS code by default we don’t get any type checking. For example we can call a function without supplying an argument and we will not know about issue until run time. So we have to compile and run our program to see result like NaN.
We can go back to tsconfig.json and turn on “checkJs”: true
Now we get some basic type checking. it is not complete but is better than nothing
js file:
export function getNumber(num){
return num*10
}
Ts file:
import { getNumber } from "./myFanc";
const myNumber = getNumber(2);
console.log(myNumber);
in powershell (or command prompt):
When this setting enabled we will encounter errors in Js file.
To solve this issue we have 3 solution:
Fix JavaScript file errors
1. Ignore type checking
We can optionally turn off compiler errors on a file-by-file basis by applying // @ts-nocheck once on top of JavaScript files.
2. Describing types using JSDoc
One way to describe type information our Js code is using JSDoc that is a special type of comment.
By using JSDoc we can provide type information to the typescript compiler and we can explain our code. For example:
/**
* Multiply the number by ten
* @param {number} num - value after calculation
* @returns {number} - return value
*/
export function getNumber(num){
return num*10
}
3. Creating declaration files
Another way to provide type information is to use Decoration for type definition files. We create a new file called ‘same name as Js file’.d.ts .In this file we declare all the features of the target modules. Type definition files are similar to header files in C.
myfunc.d.ts
export declare function getNumber(num: number): number;
using definitely type declaration files
We don’t need to create type definition files for third-party JavaScript libraries. We can use type definition files from the Definitely Typed GitHub repository (@types/ ).
Thank you for reading this post! :)
z. Nabi
Top comments (0)