You can utilize Typescript to create .d.ts
definition files for your local javascript files. Consider the following file structure:
src/
main.js
imported.js
imported.d.ts
main.js
import { func } from './imported';
console.log(func("1", "1"));
imported.js
export const func = (numVal, strVal) =>
`The number is ${numVal}, the string is ${strVal}`;
imported.d.ts
export const func: (numVal: number, strVal: string) => string;
When using the noImplicitAny
option, you may encounter errors like:
src/imported.js(1,22): error TS7006: Parameter 'numVal' implicitly has an 'any' type.
src/imported.js(1,30): error TS7006: Parameter 'strVal' implicitly has an 'any' type.
src/main.js(3,18): error TS2345: Argument of type '"1"' is not assignable to parameter of type 'number'.
The last error ensures type safety by preventing passing a string instead of a number as required. However, in the imported javascript file, the parameters' types are not recognized, hindering the use of noImplicitAny and potentially leading to errors when passing incorrect types.
Is there a way to enable javascript files to acknowledge their definitions in Typescript without altering the original javascript code?