DEV Community

Discussion on: TypeScript vs. JSDoc JavaScript for static type checking

Collapse
peerreynders profile image
peerreynders • Edited on

Compared to the equivalent JSDoc JavaScript

The code you are showing is "using plain JSDoc" vs "using JSDoc to reference TS types" for static type checking/linting.

In the latter the types are defined in .d.ts files — i.e. the declarations exist in "type space" while JSDoc style annotations are used to reference the TS types in "value space" (the JavaScript files).

Example (Discriminate Union with Exhaustiveness checking):

// file: tutorial.d.ts
//
type TutorialInfo = {
  topic: string;
};

export type VideoTutorial = TutorialInfo & {
  kind: 'video';
  duration: number;
};

export type PdfTutorial = TutorialInfo & {
  kind: 'pdf';
  pages: number;
};

export type Tutorial = VideoTutorial | PdfTutorial;

declare function take(t: Tutorial): void;

export { take };
Enter fullscreen mode Exit fullscreen mode
// file: tutorial.js
//
/** @typedef { import('./tutorial').take } TypeTake */

/** @type { TypeTake } */
function take(tutorial) {
  switch (tutorial.kind) {
  case 'video':
    console.log(`Watch Video: ${tutorial.topic}`);
    break;

  case 'pdf':
    console.log(`Read PDF: ${tutorial.topic}`);
    break;

  default:
    /** @type { never } */
    const _exhaustiveCheck = tutorial;
  }
}

export { take };
Enter fullscreen mode Exit fullscreen mode
// file: index.js
//
import { take } from './tutorial.js';

/** @type { import('./tutorial').VideoTutorial } */
const v = {
  kind: 'video',
  topic: 'In The Loop',
  duration: 3081,
};

/** @type { import('./tutorial').PdfTutorial } */
const p = {
  kind: 'pdf',
  topic: 'Modern Asynchronous JavaScript',
  pages: 75,
};

take(v); // "Watch Video : In The Loop"
take(p); // "Read PDF: Modern Asynchronous JavaScript"
Enter fullscreen mode Exit fullscreen mode

Note how:

  • types are imported from type space into value space, e.g. import('./tutorial').VideoTutorial
  • typedef is used to make an imported type available in the entire file.
  • type is used to reference/formulate the type in the style of TS (rather than JSDoc).