This is short "How To" on using the awesome type safety of Typescript in Vanilla JS.
It is an extremely flexible option for adding typing to JS and requires very little setup and no build process.
You basically add a comment to the top of a file to enable checking and then annotate functions, variables, objects and classes as needed.
When ts-check is enabled, you also get implicit type checking for anything that VS Code can infer.
At the top of your js file add the following comment
//@ts-check
Add this to your settings.json
in vs cod, shortcut via cmd + ,
{
"js/ts.implicitProjectConfig.checkJs": true,
}
This will enable ts-check on all your js files by default. To explicitly opt out of type checking add this to a file:
//@ts-nocheck
Annotate next line:
/** @type {string} */
var myVarAsString = dataFromSomethingFnCall();
Annotate inline - note use of parens to wrap expression:
var myVarAsNumber = /** @type {number} */(dataFromSomethingFnCall());
/** @type {__TYPE__} */
/** @type {__TYPE__} */ ()
/**
* @param {string} a
* @return {string}
*/
const myFun = (a, b) => {
// code
return something();
}
Typing this
/**
* @this {MyType}
* @param {string} a
* @param {number} b
* @return {number}
*/
function(a, b) {
//...code
}
/**
* @param {__TYPE__} __NAME__
* @return {__TYPE__}
*/
To Create a Custom Type
/**
* @typedef { "NORTH" | "EAST" | "SOUTH" | "WEST" } CompassDirection
*/
To Create an Interface
/**
* @typedef {Object} IAwesomeType
* @property {string} keyA
* @property {number} keyB
* @property {CompassDirection} keyC
* @property {IMyOtherInterface} keyD
*/
/**
* @typedef {Object} __NAME__
* @property {__TYPE__} __NAME__
*/
class CoordinatePoint {
/**
* @param {number} x
* @param {number} y
*/
constructor(x, y) {
// ...
}
/**
* @return {number}
*/
getX() {
// ...
}
/**
* @return {number}
*/
getY() {
// ...
}
/**
* @param {string} str
* @return {CoordinatePoint}
*/
static fromString(str) {
// ...
}
}
You can import from typescript or TS type definition files with the following annotation
IAwesomeType
would be available for use in the current file after doing this.
/**
* @typedef {import("./to/my/path/file.d.ts").IAwesomeType} IAwesomeType
*/