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:
Top comments (6)
@jfbrennan you can add an explicit return type:
There's even an eslint rule to make it mandatory (which I highly recommend).
Shouldn't it be "You don't need Typescript when you have types in JSDoc" instead?
I don't think so, typescript provides more than javascript with jsdoc could
Actually it's the other way around. Not only can JSDoc handle types, it simultaneously handles documentation, all without extra tooling. It's beautiful. All you're saying here is that you haven't tried it properly.
How can I create classes, use composition and inheritance, IoC and all the well documented patterns in object oriented programming using JsDocs?
Javascript was originally created for simple scripts on the web, it's very difficult to scale server-side projects (and even modern web projects) where you have to maintain and share modules between different teams.
You're kidding, right?