【问题标题】:Constraining jsdoc/typescript type to an array member将 jsdoc/typescript 类型限制为数组成员
【发布时间】:2020-04-29 00:58:29
【问题描述】:

我在 jsdoc 中使用 typescript,并试图将一个变量限制为我在数组中拥有的一组已知值中的一个。

我知道我可以这样做:

/** @type {'one'|'two'|'three'} */
let v = 'four';
// ==> Error, type 'four' is not assignable to type 'one'|'two'|'three'

就我而言,我在数组附近有所需的值。为了避免重新输入,我想以某种方式引用它们,但我不知道这是否可能。我想要这样的东西:

const OPTIONS = ['one', 'two', 'three'];

/** @type {string<Options>} */
let v = 'four';
// ==> Desired -- Error, type 'four' is not assignable to type 'one'|'two'|'three'
// ==> but that doesn't actually work...

有没有办法做到这一点?

【问题讨论】:

    标签: typescript jsdoc


    【解决方案1】:

    我认为你不能用数组来实现这一点,因为它们在运行时是可变的:

    const OPTIONS = ['one', 'two', 'three'];
    OPTIONS[0] = 'BOOM';
    

    但是,您可以将数组更改为元组(元组是不可变的):

    const OPTIONS = ['one', 'two', 'three'];                
    const OPTIONS_TUPLE = ['one', 'two', 'three'] as const;
    

    比较推断类型:

    // const OPTIONS: string[]
    // const OPTIONS_TUPLE: readonly ["one", "two", "three"]
    

    现在,你可以检索你想要的类型了:

    const OPTIONS_TUPLE = ['one', 'two', 'three'] as const;
    type OptionsValue = typeof OPTIONS_TUPLE[number];
    const x: OptionsValue = 'four'; 
    //TS2322: Type '"four"' is not assignable to type '"one" | "two" | "three"'.
    

    【讨论】:

    • 谢谢,真的很有帮助。不幸的是,看起来 as const 目前在 jsdoc 语法中不可用,但我会密切关注这一点。 github.com/Microsoft/TypeScript/issues/30445 将问题留待一段时间,以防目前有其他可能的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2021-04-12
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    相关资源
    最近更新 更多