Skip to content

Practical examples to use JSDoc to define typed variables in javascript

License

Notifications You must be signed in to change notification settings

sselvaggi/vsc-typed-but-not-transpilled-javascript

Repository files navigation

VSC Typed (but not transpilled) Javascript

Thanks to VSC we can use almost every Typescript feature directly inside Javascript files thanks to JSDoc annotations

Update 2022: Microsoft proposal at ECMAScript to implement typing on runtime using annotations

Types definitions help to structure the code giving better autocomplete in code editors like VSC.

There're 2 alternatives to have full typescript support at .js files

  • Adding this comment at the top of the .js file:
// @ts-check

OR

  • Creating jsconfig.json with the same info as tsconfig.json in the root of the project
{
  "compilerOptions": {
    "allowJs": true,
    "esModuleInterop": true,
    "checkJs": true,
    "module": "ES2022",
    "target": "ES6",
    "typeRoots": ["src/types"],
    "lib": ["DOM"],
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "jsx": "preserve"
  },
  "exclude": ["node_modules", "./src/_ui"]
}

We can import type definitions from .ts files (only types and interfaces), even from 3rd party libraries inside our project.

Import types

/**
 * @typedef {import('./filePath').default} MyType
 */

Setting variable type

const x = /** @type {MyType} */ (value);

IMPORTANT don't forget to souround value inside parenthesis around value.

Samples

01-functions

01_Functions

02-imports

02_imports

03-namespaces

03_Namespaces

04-generics

04_Generics

05-Observers

05_Observers

06-schemas

06_Schemas

About

Practical examples to use JSDoc to define typed variables in javascript

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published