如何使用 JSDoc 在 javascript 中转换 TypeScript 类型

How to cast TypeScript type in javascript using JSDoc

使用 TypeScript 检查 JavaScript 代码时,如何转换为不同于推断的类型? Typescript 具有 <Type>as Type 语法,但这些语法在 JavaScript.

中无效
/**
 * @param {{id: string, value: number}} details - object with required properties
 */
function stringifyObject(details) {
  return `${details.id}: ${details.value}`;
}

const testValue = {id: 'no-value'};
stringifyObject(testValue); // want to cast testValue to ignore missing property
stringifyObject(/** @type {any} */ testValue); // this doesn't work

/** @type */ 评论已关闭。根据 TypeScript Handbook 它只需要在所投值周围加上括号。

TypeScript borrows cast syntax from Google Closure. This lets you cast types to other types by adding a @type tag before any parenthesized expression.

所以在原来的例子中你会写成下面这样:

// Wrap value being cast in parenthesis 
stringifyObject(/** @type {any} */ (testValue));