繁体   English   中英

在 JSDoc 中键入断言 function

[英]Type asserting function in JSDoc

我正在尝试提出以下 TypeScript 类型断言 function 的 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 function,当传递一个unknown时,将仅使用 TypeScript 类型干扰和逃逸分析验证并返回未知的 object 类型作为提供的类型?

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

TS 3.7 中引入的断言函数可以在调用 scope 时断言值的类型。

/**
 * @param {*} maybeString
 * @returns {asserts maybeString is string}
 */
function assertString(maybeString) {
  if (typeof maybeString !== 'string') throw Error('not a string');
}

/**
 * @param {unknown} something
 */
function demo(something) {
  something.concat; // type error
  assertString(something);
  something.concat; // valid
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM