Last active
August 5, 2023 04:45
-
-
Save ayoayco/35d32ec5e25e9cf9adcffc02b06265a7 to your computer and use it in GitHub Desktop.
Type-checking vanilla JS with JSdoc and the TS typechecker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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'. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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'. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.