下面是一个 Typescript 函数签名 x,它接受 ABC 作为可选参数。如果传入 ABC,则 a 和 b 为必填字段。
async x (options: ABC = {}): Promise<string>
interface ABC {
a: string
b: number
}
JSDOC 应该是这样的吗
/**
* @param {ABC} [options]
* @param {string} options.a
* @param {number} options.b
* @return {Promise<string>}
*/
或者这个
/**
* @param {ABC} [options]
* @param {string} [options.a]
* @param {number} [options.b]
* @return {Promise<string>}
*/
在
ABC
的 JSDoc 中记录 ABC
的结构,而不是在 x
的 JSDoc 中:
interface ABC {
/**
* describe `a` here
*/
a: string
/**
* describe `b` here
*/
b: number
}
/**
* @param {ABC} options
* @return {Promise<string>}
*/
async function x (options: ABC): Promise<string> {
// IOU a promise
}
如果没有任何关于
ABC.a
或 ABC.b
的内容,您可以完全跳过该 JSDoc。 Typescript 和您的 Typescript IDE 已经知道 a
是一个字符串,b
是接口定义中的数字。即使您提出的 JSDoc 是正确的(事实并非如此),它也是多余的。
📌问题中
x
的签名会产生错误,所以我不得不猜测你的意图。请参阅我在问题下的评论。
为了澄清并可能软化 Inigo 的观点, 没有必要在 JSDoc 中提供类型定义 使用 TypeScript 时。如果您为您的
options
创建一个界面
参数并使用 JSDoc(您的 Typescript IDE)记录它
将提供参数的自动完成和文档。
然而,更重要的是,我们不要忘记, 文档是为了帮助开发人员使用您的代码——而不仅仅是提供 类型定义。作为一个例子,我写了一个工作 (如果不是完全愚蠢)功能并添加了一些文档:
/**
* Provides options for {@link dumbSubstring}.
*/
declare interface DumbSubstringOptions {
/** The `start` index for {@link dumbSubstring}. */
start?: number;
/** The `end` index for {@link dumbSubstring}. */
end?: number;
/**
* If {@link dumbSubstring} should reject if the value of {@link end}
* is greater than the string length.
*/
rejectOnInvalidLength?: boolean;
/** If {@link dumbSubstring} should reject if `val` is an empty string. */
rejectOnEmptyString?: boolean;
}
/**
* Substrings a value.
* @param val A string to `substring()`
* @param options (optional) Provides additional options.
* @return A promise of the `substring` operation.
*/
async function dumbSubstring(
val: string,
options?: DumbSubstringOptions
): Promise<string> {
return new Promise((resolve, reject) => {
if (options?.rejectOnEmptyString && val.length === 0) {
reject(new Error("val is an empty string."));
}
if (options?.rejectOnInvalidLength && (options.end ?? 0) > val.length) {
reject(new Error("end parameter is greater than the length of val."));
}
if (options?.rejectOnInvalidLength && (options.start ?? 0) > val.length) {
reject(new Error("start parameter is greater than the length of val."));
}
resolve(val.substring(options?.start ?? 0, options?.end));
});
}
当我调用该函数时,VSCode 显示可用选项:
当我将鼠标悬停在某个选项上时,VSCode 会显示其 JSDoc: