声明引用
某些标签,例如{@inheritdoc}
和 {@link}
,可以引用其他 API 项目,例如类、成员函数、枚举值等。引用的项目可能是本地的,也可能是从外部 NPM 包导入的。它可能是合并声明的一部分,也可能是重载函数的一部分。
TSDoc 语法提供了一种特殊的“**声明引用**”表示法,用于在所有这些情况下明确识别声明。(TSDoc 的这方面仍在发展中;它由 RFC #9 跟踪。当前规范概述在 code-snippets/DeclarationReferences.ts 中。)
语法示例
以下是帮助你开始编写声明引用的语法示例。
简单的本地声明
/** @public */
export class Widget {
/**
* Call this before calling the {@link Widget.render | the render() method}.
*/
public initialize(): void {}
public render(): void {}
}
要引用同一个项目中的声明,只需使用它的名称,并用“.”来限定任何嵌套的成员。在上面的例子中,Widget.render
指的是Widget
类中的render
方法。只要匹配是明确的,static
成员与否就无关紧要了。
TSDoc 声明引用始终相对于特定的入口点解析(而不是相对于当前源文件或声明作用域)。因此,它们的语法与引用在给定包中的位置无关。由于
Widget.initialize
位于Widget
内部,我们可能希望将引用缩短为{@link render | the render() method}
,但 TSDoc 标准不支持此操作。
导入的声明
import { Widget } from '@my-org/widget-lib';
/**
* Returns a new instance of the {@link @my-org/widget-lib#Widget} class.
* @public
*/
export function createWidget(): Widget {
. . .
}
要引用从 NPM 包导入的声明,请指定包名称,后跟#
字符(例如 widget-lib#Widget
)。如果包名称具有 NPM 范围,也可以将其包括在内(例如 @my-org/widget-lib#Widget
)。
整个包
import { Button } from 'controls';
/**
* Constructs a `Button` as defined by the {@link controls#} library.
* @public
*/
export function createButton(): Button {
. . .
}
要引用整个包(而不是特定导出),只需省略上面显示的成员名称。但是,你必须包含#
字符,否则 controls
看起来像对名为 controls
的声明的引用。
合并的声明
/** @public */
export enum ShirtSize {
Small,
Medium,
Large
}
/** @public */
export namespace ShirtSize {
/**
* Parses a string and returns an instance of the
* {@link (ShirtSize:enum)} enum.
*/
export function parseName(name: string): ShirtSize {
switch (name) {
case 'S':
return ShirtSize.Small;
case 'M':
return ShirtSize.Small;
case 'L':
return ShirtSize.Large;
}
throw new Error('Invalid size');
}
}
在上面的例子中,符号ShirtSize
既是枚举,又是命名空间。如果我们简单地写{@link ShirtSize}
,API Extractor 将报告类似这样的警告
Warning: (ae-unresolved-link) The @link reference could not be resolved:
The reference is ambiguous because "ShirtSize" has more than one declaration;
you need to add a TSDoc member reference selector
(ShirtSize:enum)
表示法使用 TSDoc 系统选择器来明确我们指的是枚举,而不是命名空间。
不支持的功能
API Extractor 支持 TSDoc 声明引用的所有核心功能,但尚未支持规范中描述的一些高级功能
- 索引选择器
- 标签选择器
- 使用 ECMAScript 符号而不是标识符的引用
- 导入路径
这些功能可能在未来实现。如果你想贡献,请查看 AstReferenceResolver.ts 和 ModelReferenceResolver.ts 中的代码。