将jsdoc / typescript类型限制为数组成员

问题描述 投票:0回答:1

[我在jsdoc中使用打字稿,并试图将变量限制为数组中具有的一组已知值中的一个。

我知道我可以这样:

/** @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个回答
0
投票

我认为您无法使用数组来实现,因为它们在运行时是可变的:

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"'.
© www.soinside.com 2019 - 2024. All rights reserved.