Research notes regarding converting JSDoc to TypeScript types

A lot of my JS code had been typed with JSDoc comments.
JSDoc comments are very useful for typing JavaScript code, and also have the benefit of allowing inline TypeScript types and importing TypeScript types from ts files. Types can be checked easily in modern editors such as VSCode. For example, the code below, imports from a ts file and types the variable.

/**
* @type {import('tsfile.ts').MyType}
*
const myVariable = 'abc';

It is also possible to declare the type using @typedef to reuse within the file.

/**
* @typedef {import('tsfile.ts').MyType} MyType
*

/*
* @type {MyType}
*/
const myVariable = 'abc';

However, one big issue with JSDoc is that importing it from external libraries seems to not work.
TypeScript types seem to be usable without any processing by just referencing the file such as:

/**
* @typedef {import('my-library'/ts-file-location.ts).MyType} MyType
*/

For JSDoc, generate type declaration files seems to be required.
This is fine, and is expected for JS projects, but it is an extra step that needs to be prepared for all JS projects.

Considering, TypeScript can be imported into JSDoc in the first place, there is really no reason to store type files using JSDoc. The solution is then to isolate types into type only files in ts, and then export each type. This makes it easy to import into JSDoc and into other projects without and processing.

Searching for solutions to convert JSDoc to TypeScript did take my down and long-winding road of issues, that seems to not have been worth the trouble. I have written any significant information in the notes below, but the solution is to just use tsc from TypeScript. See below.

TypeScript tsc

  • Seems to work best. Just need to add exports if necessary and extract from generated file(s).
# Update [SOURCE] below.
# tsc [SOURCE] --declaration --emitDeclarationOnly --allowJs
#
# Notes:
# -- outFile [BUNDLE_DESTINATION] // Works for only some code, so use optionally. https://www.typescriptlang.org/tsconfig/#outFile
# .d.ts file is created in same location with same name before extension.
# To create ts file with exports, SHOULD remove the ".d" part for declaration file, and replace each "type " with "export type ".
# MAY do the same for "interface", but seems like not used (maybe if specifically specified in JSDOC as interface?).
# To prevent replacing wrong code within comments/strings, etc., check that "type" starts at beginning of line.

Notes

ts-migrate

ts-fix

TypeScript codefixes

Other

Leave a Reply

Your email address will not be published. Required fields are marked *