Here are some basic tips for beginners trying to use TypeScript tooling against plain JavaScript + JSDoc files.
TypeScript-style documentation syntax is JSDoc, it's just a different dialect of JSDoc as far as which
JSDoc tags have formally defined behavior, what the types are (there are many more available in
the TypeScript flavor), and what the allowable syntax is (the TypeScript team tried to hew closely
to JSDoc, but they avoided @module
in favor of allowing import()
of third party types and they
don't yet support certain tags
in a type-aware way--though for doc tools unrelated to type-checking it might not matter).
See https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html for some details.
See typedoc for example which is based on a TSDoc standard, a formalization of the JSDoc-inspired comments in TypeScript.
For type-checking plain JS + JSDoc, as it is a little quirky but still doable...
If you wish to check your plain JavaScript + JSDoc for types, beyond ensuring you have function/class JSDoc and such, you may need to do some JSDoc "casting" (note the required use of parentheses), but you can mostly get by without needing to refactor anything.
You can use the npm typescript
package itself (which includes the command line tsc
, i.e., the
TypeScript compiler) with the checkJs
option to do such checking of plain JS + JSDoc for type errors
though you can also optionally avoid the type-checking part and just use tsc
to build
declaration files
for plain JavaScript which allow projects importing your npm code to know your types (or you can
do both). One doesn't have to write TypeScript syntax to take advantage of it--just
TypeScript-flavored JSDoc.
But there are still some bumps I wish TypeScript would fix to really help one solely use JSDoc inline with one's JavaScript, and avoid modifying generated declaration files. I'm pretty new to this process, but two significant bugs which I've come across relate to the fact that:
@typedef
will export types whether you want them exported to 3rd parties or not, though this is not as problematic as...- If you need to specify you are exporting a class of a given type, but that class isn't global, you can't really do so (at least without creating a dummy global class)
But for simpler scenarios, it seems to mostly work. One other gotcha though is that @typedef
inheritance doesn't work. You can usually use the intersection operator (&
) instead within a
@typedef
, however.
The fact that a class has a constructor type and also a typeof
that describes it otherwise
can be a little confusing also.