【发布时间】: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