当使用 TypeScript 检查 JavaScript 代码时,如何转换为与推断不同的类型?打字稿有<Type>
and 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
The /** @type */
评论很接近。根据TypeScript 手册 https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#casts它只需要在被转换的值周围加上括号。
TypeScript 借用了 Google Closure 的强制转换语法。这允许您通过添加一个类型将类型转换为其他类型@type
tag 在任何带括号的表达式之前.
因此,在最初的示例中,您将编写以下内容:
// Wrap value being cast in parenthesis
stringifyObject(/** @type {any} */ (testValue));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)