Skip to content

Instantly share code, notes, and snippets.

@ayoayco
Last active August 5, 2023 04:45
Show Gist options
  • Save ayoayco/35d32ec5e25e9cf9adcffc02b06265a7 to your computer and use it in GitHub Desktop.
Save ayoayco/35d32ec5e25e9cf9adcffc02b06265a7 to your computer and use it in GitHub Desktop.
Type-checking vanilla JS with JSdoc and the TS typechecker
// @ts-check
/**
* @typedef {string | number | boolean | null | undefined} Primitive
*/
/**
* @template { Primitive } T
* @template {T | Record.<string,T>} R
* @param {R} v
* @returns {R}
*/
const freeze = (v) => (v)
const person = freeze({
name: 'Ayo',
age: 14
});
person.name = 'Anything else' // ERROR: Type '"Anything else"' is not assignable to type '"Ayo"'.
person.age = 15 // ERROR: Type '15' is not assignable to type '14'.
// @ts-check
let nickName = 'Ramon'; // here type is inferred as string
nickName = 1; // ERROR: Type 'number' is not assignable to type 'string'.
/** @type{string} */ // explicit type setting
let title;
title = 1; // ERROR: Type 'number' is not assignable to type 'string'.
@ayoayco
Copy link
Author

ayoayco commented Aug 5, 2023

This solution will need your (and your teammate's) IDE's TypeScript typechecker to understand JSdoc. Fortunately, popular IDEs and code editors like VS Code can do this out of the box if you're already coding TypeScript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment