JSDoc中的类型断言函数

6

我正在尝试编写一个JavaScript+JSDoc版本的以下TypeScript类型断言函数:

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并不感兴趣,但特别是在使用JSDoc进行类型提示的JavaScript项目中,结合TypeScript语言服务与Visual Studio Code一起使用。

2个回答

7

3

有人在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}'!`)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接