【问题标题】:How to cast TypeScript type in javascript using JSDoc如何使用 JSDoc 在 javascript 中转换 TypeScript 类型
【发布时间】:2022-01-03 04:01:26
【问题描述】:

当使用 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

【问题讨论】:

    标签: typescript jsdoc


    【解决方案1】:

    /** @type */ 评论已关闭。根据TypeScript Handbook,它只需要在被转换的值周围加上括号。

    TypeScript 借鉴了 Google Closure 的强制转换语法。这允许您通过在任何带括号的表达式之前添加@type 标签,将类型转换为其他类型。

    因此,在原始示例中,您将编写以下内容:

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

    【讨论】:

    • 正是我需要的,谢谢!
    猜你喜欢
    • 2020-11-17
    • 2012-10-23
    • 2020-02-07
    • 2019-02-03
    • 2018-02-01
    • 2021-04-12
    • 2021-06-07
    • 2014-04-08
    相关资源
    最近更新 更多