Item 80: Use @ts-check and JSDoc to Experiment with TypeScript
May 10, 2024 ยท View on GitHub
Things to Remember
- Add "
// @ts-check" to the top of a JavaScript file to enable type checking without converting to TypeScript. - Recognize common errors. Know how to declare globals and add type declarations for third-party libraries.
- Use JSDoc annotations for type assertions and better type inference.
- Don't spend too much time getting your code perfectly typed with JSDoc. Remember that the goal is to convert to .ts!
Code Samples
// @ts-check
const person = {first: 'Grace', last: 'Hopper'};
2 * person.first
// ~~~~~~~~~~~~ The right-hand side of an arithmetic operation must be of type
// 'any', 'number', 'bigint' or an enum type
// @ts-check
console.log(user.firstName);
// ~~~~ Cannot find name 'user'
interface UserData {
firstName: string;
lastName: string;
}
declare let user: UserData;
// @ts-check
$('#graph').style({'width': '100px', 'height': '100px'});
// Error: Cannot find name '$'
// @ts-check
$('#graph').style({'width': '100px', 'height': '100px'});
// ~~~~~ Property 'style' does not exist on type 'JQuery<HTMLElement>'
// @ts-check
const ageEl = document.getElementById('age');
ageEl.value = '12';
// ~~~~~ Property 'value' does not exist on type 'HTMLElement'
// @ts-check
const ageEl = /** @type {HTMLInputElement} */(document.getElementById('age'));
ageEl.value = '12'; // OK
// @ts-check
/**
* Gets the size (in pixels) of an element.
* @param {Node} el The element
* @return {{w: number, h: number}} The size
*/
function getSize(el) {
const bounds = el.getBoundingClientRect();
// ~~~~~~~~~~~~~~~~~~~~~
// Property 'getBoundingClientRect' does not exist on type 'Node'
return {width: bounds.width, height: bounds.height};
// ~~~~~ Type '{ width: any; height: any; }' is not
// assignable to type '{ w: number; h: number; }'
}
// @ts-check
/**
* @param {number} val
*/
function double(val) {
return 2 * val;
}
function loadData(data) {
data.files.forEach(async file => {
// ...
});
}
/**
* @param {{
* files: { forEach: (arg0: (file: any) => Promise<void>) => void; };
* }} data
*/
function loadData(data) {
// ...
}