DEV Community

Andreas Sander
Andreas Sander

Posted on • Originally published at andi1984.dev

Starting with TypeScript via JSDoc

In this post it is all about a very interesting technique to use the typing definition of TypeScript without doing a full buy-in for TypeScript.

JSDoc

JSDoc 3 is an API documentation generator for JavaScript[...]
-- JSDoc

So most probably you are already using JSDoc for documenting your code. If you don't, you should definitely do!

JSDoc Typedefs

You might also know that JSDoc provides a way to declare custom types via the @ŧypedef keyword.

So we could get something like this:

/**
 * A number, or a string containing a number.
 * @typedef {(number|string)} NumberLike
 */

/**
 * @type NumberLike
 */
const number = 2;
Enter fullscreen mode Exit fullscreen mode

But you might not know that you can also import type definitions within the curly braces of the @typedef rule, did you? I also didn't...

TypeScript

That is where TypeScript comes into play:

Example:

File: typings.ts

export type Car = {
  manufacturer: string;
  series: string;
};
Enter fullscreen mode Exit fullscreen mode

With this we simply importing those TS-based type definitions as a JSDoc type definition:

File: foo.js

/**
 * @typedef {import("./typings").Car} Car
 */

/**
 * @type {Car}
 */
const porsche911Carrera4S = { manufacturer: 'Porsche', series: 'Porsche 993' };
Enter fullscreen mode Exit fullscreen mode

I have also created a small Github Gist where you can see all code at a glance.

Benefits

Let us be honest... The shown solution here is a trade-off between having no typed language at all or having a 100% TypeScript codebase. Thus this approach will never be as sophisticated as a 100% TS approach, but definitely better in terms of linting, autocompletion and type hints in VSCode as you would have with a plain JS file.

In case you have a huge, complex project with a team behind and you want to dig into type definitions to get some better feeling, understanding and experience with TypeScript, this approach might help you to start getting your fingers dirty.

Book Recommendation

As you seem to be interested in TypeScript I would like to recommend you a newly released book written by Stefan Baumgartner called "TypeScript in 50 lessons". But also his blog https://fettblog.eu is an amazing source of TypeScript lessons. Check it out!

Cheers,

Andi

Top comments (2)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

If you want to have TypeScript warnings, not just typings, you will always need // @ts-check (AFAIK).

Collapse
 
andi1984 profile image
Andreas Sander

@patarapolw That is absolutely correct.