Why You Don't Need Types in JSDoc when Documenting TypeScript
Kamran Ayub
Posted on February 5, 2020
I work with many folks who are coming from native JavaScript and learning TypeScript and I've noticed one small thing during code reviews that can save some time. Here's a quick tip if you're used to writing "regular" JSDoc!
One huge benefit of using TypeScript and documenting with JSDoc syntax is that you can avoid having to specify JSDoc types in your docs! If you want to read the full specification check out Microsoft's standard, tsdoc.
Here's an example of a native JavaScript function with JSDocs:
/**
* Clamps a `value` between a `min` and `max` inclusive
*
* @param {Number} value The value to clamp between `min` and `max`
* @param {Number} min The minimum number of the range
* @param {Number} max The maximum number of the range
*
* @returns {Number} The clamped value
*/
export function clamp(value, min, max) {
return Math.min(Math.max(min, value), max);
}
In TypeScript, you're already statically typing your arguments and return type so there's no need to repeat them in the JSDoc. Lose 'em!
/**
* Clamps a `value` between a `min` and `max` inclusive
*
* @param value The value to clamp between `min` and `max`
* @param min The minimum number of the range
* @param max The maximum number of the range
*
* @returns The clamped value
*/
export function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(min, value), max);
}
Bonuses:
- A refactor-rename (
F2
in Visual Studio Code) of a param will sync the JSDoc param names for you - VS Code has autocomplete suggestions for parameter names as you type your JSDocs
- VS Code and many other tools support Markdown in JSDoc
Here's what you'll see in your editor now:
Posted on February 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.