Home

Awesome

JSDoc Typing

Companion code to the "All the benefits of TypeScript, with none of the drawbacks" blog post on https://gils-blog.tayar.org.

This repo is an example of how to use JSDoc to get all the benefits of TypeScript, without the drawbacks of transpiling.

This package is an example package that both uses and exports JSDoc typings.

The interesting things in this package are:

Package.json

The package.json is where we tie everything together.

types property

  "types": "./types/jsdoc-typing.d.ts",

This property tells TypeScript where the type definitions file for this package is, so that if another package npm install-s this package, it will find the type definitions. These type definitions are generated by:

  "scripts": {
    "build": "rm -rf types/* && tsc  --noEmit false --emitDeclarationOnly true && cp src/*.d.ts types",
  }

This build script first cleans the types folder, then generates the types using tsc, and then copies the .d.ts files to the types directory because TypeScript doesn't.

Typechecking here is done in the test script by calling the TypeScript compiler, thus:

  "scripts": {
    "test": "tsc",
  },

don't forget to npm install --save-dev typescript to get the compiler!

Last, but not least, we enable publishing the types directory so that importing packages will find it:

  "files": [ "src", "types" ]

tsconfig.json

The tsconfig.json is the file that defines how TypeScript typechecks the JS files:

{
  "compilerOptions": {
    "lib": ["es2020", "DOM"],
    "moduleResolution": "node",
    "module": "CommonJS",
    "resolveJsonModule": true,
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "strict": true,
    "declarationDir": "types",
    "declaration": true
  },
  "include": ["src/**/*.js", "src/**/*.d.ts"],
  "exclude": ["node_modules"]
}

You can add other properties from the regular TypeScript tsconfig.json. You can find the reference documentation for all properties here.

global.d.ts

The .d.ts file in the src directory that includes the declare module '...' for all modules that have no type definitions, so that TypeScript will not error when require-ing them.

Other .d.ts files

Use other .d.ts files to export interface-s and other TypeScript type definitions that you cannot define using JSDoc typings.

You are not allowed to add this to the a .d.ts file that includes declare module so keep these separate from global.d.ts.