Thanks to VSC we can use almost every Typescript feature directly inside Javascript files thanks to JSDoc annotations
Update 2022: Microsoft proposal at ECMAScript to implement typing on runtime using annotations
Types definitions help to structure the code giving better autocomplete in code editors like VSC.
There're 2 alternatives to have full typescript support at .js files
- Adding this comment at the top of the .js file:
// @ts-check
OR
- Creating jsconfig.json with the same info as tsconfig.json in the root of the project
{
"compilerOptions": {
"allowJs": true,
"esModuleInterop": true,
"checkJs": true,
"module": "ES2022",
"target": "ES6",
"typeRoots": ["src/types"],
"lib": ["DOM"],
"moduleResolution": "node",
"resolveJsonModule": true,
"jsx": "preserve"
},
"exclude": ["node_modules", "./src/_ui"]
}
We can import type definitions from .ts files (only types and interfaces), even from 3rd party libraries inside our project.
/**
* @typedef {import('./filePath').default} MyType
*/
const x = /** @type {MyType} */ (value);
IMPORTANT don't forget to souround value inside parenthesis around value.