Today I learned you can type check JS files by adding this line to the top of a file:
//@ts-check
const something = ['hello', 'there'];
something.push(1);
Since something
is inferred to be an array of strings, we shouldn’t be able to push a number to the array. Therefore, we get a little red squiggle under 1.
You can also type things using jsdocs.
/**
* @param {string} unsauced
* @returns {string}
*/
const awesomeSaucify = unsauced => {
return `${unsauced} is awesome sauce.`;
};
If you write a function but forget to type the parameters, you’ll get a little warning underline similar to what happens in typescript. So that serves as a friendly reminder to type your functions.