【问题标题】:Type asserting function in JSDocJSDoc 中的类型断言函数
【发布时间】:2021-06-15 01:34:47
【问题描述】:

我正在尝试提出以下 TypeScript 类型断言函数的 JavaScript+JSDoc 变体:

function typeCheck<T>(value: unknown, type: new () => T) {
    if (value instanceof type) {
        return value;
    }

    throw new Error('Invalid type');
}

const maybeButton: unknown = document.createElement('button');
const button = typeCheck(maybeButton, HTMLButtonElement);

我想出了这个,但我收到了一个错误:

/** @template T */
/** @returns {T} */
export default function check(/** @type {unknown} */ object, /** @type {new () => T} */ type) {
  if (object instanceof type) {
    /** @type {any} */
    const any = object;

    /** @type {T} */
    const t = any;

    return t;
  }

  throw new Error(`Object ${object} does not have the right type '${type}'!`)
}

错误在调用站点:const button = check(event.currentTarget, HTMLButtonElement);HTMLButtonElement 带有下划线,错误消息显示:

Argument of type '{ new (): HTMLButtonElement; prototype: HTMLButtonElement; }' is not assignable to parameter of type 'new () => T'.
  Type 'HTMLButtonElement' is not assignable to type 'T'.
    'T' could be instantiated with an arbitrary type which could be unrelated to 'HTMLButtonElement'.ts(2345)

是否可以开发像这样的 JSDoc 函数,当传递 unknown 时,将仅使用 TypeScript 类型干扰和转义分析验证并返回类型为提供类型的未知对象?

我一般对 JSDoc 不感兴趣,但特别是在 Visual Studio Code 中使用的 JSDoc,TypeScript 语言服务在 JavaScript 项目中使用 JSDoc 作为类型提示。

【问题讨论】:

    标签: javascript typescript jsdoc


    【解决方案1】:

    TypeScript Discord 上的某个人帮我想出了答案:

    /**
     * @template T
     * @returns {T}
     * @param {unknown} obj
     * @param {new () => T} type
     */
    export default function assertInstance(obj, type) {
      if (obj instanceof type) {
        /** @type {any} */
        const any = obj;
    
        /** @type {T} */
        const t = any;
    
        return t;
      }
    
      throw new Error(`Object ${obj} does not have the right type '${type}'!`)
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      相关资源
      最近更新 更多