本文的翻译于<<Effective TypeScript>>, 特别感谢!! ps: 本文会用简洁, 易懂的语言描述原书的所有要点. 如果能看懂这文章,将节省许多阅读时间. 如果看不懂,务必给我留言, 我回去修改.
技巧48:用TSDoc给API添加注释
这有一个函数用于生成一个问候语:
// Generate a greeting. Result is formatted for display.
function greet(name: string, title: string) {
return `Hello ${title} ${name}`;
}
上面代码的作者非常贴心写了一段注释。告诉读者代码的功能。但是最好使用JSDoc风格的注释:
/** Generate a greeting. Result is formatted for display. */
function greetJSDoc(name: string, title: string) {
return `Hello ${title} ${name}`;
}
好处就在于,当我们调用该函数,编辑器能将注释告诉我们:
只有JSDoc风格的注释可以,第一种内联注释是做不到的:
如果使用了ts,JSDoc风格的代码注释也被称之为TSDoc注释风格。
另外我们可以使用一些标注:@param 和 @returns:
/**
* Generate a greeting.
* @param name Name of the person to greet
* @param salutation The person's title
* @returns A greeting formatted for human consumption.
*/
function greetFullTSDoc(name: string, title: string) {
return `Hello ${title} ${name}`;
}
编辑器这样提示:
类型注释也可以写注释:
/** A measurement performed at a time and place. */
interface Measurement {
/** Where was the measurement made? */
position: Vector3D;
/** When was the measurement made? In seconds since epoch. */
time: number;
/** Observed momentum */
momentum: Vector3D;
}
当你查看每个字段,也能得到提示:
TSDoc注释支持Markdown格式:
/**
* This _interface_ has **three** properties:
* 1. x
* 2. y
* 3. z
*/
interface Vector3D {
x: number;
y: number;
z: number;
}
避免在注释里写小作文,因为简洁扼要才是好注释的关键。避免在注释里写类型,因为ts已经实现了这部分功能