Description
@liamross brought up an interesting scenario in #115:
However, the fact that my documentation will have zero indication of the type of a parameter means that this could never serve as a replacement for JSDoc for me personally. If I write a library in TypeScript and it is consumed by a JavaScript application, I would like for there to be typings in the documentation, and not require that people are relying on IDE tooling or digging into the package to find types.
The first thing that drew me to this was the idea of it parsing types from the code to save the redundant declarations in the documentation.
If you build a library in TypeScript, the output includes declaration files (*.d.ts) that provide very accurate type information. (Arguably the best in the world! :-) ) However many JavaScript tools perform static type analysis based on .js files, and ignore the .d.ts files.
These tools generally expect to obtain their type information from JSDoc tags such as this sample that I pulled from a random blog post:
/** @namespace */
var util = {
/**
* Repeat <tt>str</tt> several times.
* @param {string} str The string to repeat.
* @param {number} [times=1] How many times to repeat the string.
* @returns {string}
*/
repeat: function(str, times) {
if (times === undefined || times < 1) {
times = 1;
}
return new Array(times+1).join(str);
}
};
The TypeScript equivalent would look like this:
/** @namespace */
export namespace util {
/**
* Repeat <tt>str</tt> several times.
* @param {string} str - The string to repeat.
* @param {number} [times=1] - How many times to repeat the string.
* @returns {string}
*/
export function repeat(str: string, times: number = 1): string {
if (times === undefined || times < 1) {
times = 1;
}
return new Array(times + 1).join(str);
}
}
The JSDoc annotations such as @namespace
, {string}
, [times=1]
are redundant because we already expressed all those things using type declarations. It would be annoying for developers to have to declare everything twice. And it would be error-prone because TypeScript developers generally don't rely on the JSDoc tags themselves, so they won't notice mistakes. (In my own anecdotal experience migrating code bases, I've found that these redundant tags are very frequently incorrect or inconsistent with the TypeScript types.)
The compiler does support JSDoc type annotations, so one possible idea would be for people to use JSDoc annotations instead of type declarations for the public parts of their API, since these annotations do end up in the emitted .js files. However this would be limiting, since JSDoc's type expressions are quite limited compared to all the things you can express in TypeScript. And it would be an awkward developer experience.
The "ideal" solution would be to improve the JavaScript tools to support .d.ts files when they consume a TypeScript library. But let's assume that's impractical for various reasons. What other approaches could we use, and can TSDoc help somehow?