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

Ben*_*enj 2 jsdoc typescript

我在 jsdoc 中使用打字稿,并尝试将变量限制为数组中已知的一组值之一。

我知道我可以这样做:

/** @type {'one'|'two'|'three'} */
let v = 'four';
// ==> Error, type 'four' is not assignable to type 'one'|'two'|'three'
Run Code Online (Sandbox Code Playgroud)

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

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...
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做到这一点吗?

mus*_*.id 5

截至2021 年 8 月 28 日,可以使用 JSDoc 内联,@type {const}如下所示:

const OPTIONS = /** @type {const} */ (['one', 'two', 'three']);

/** @type {typeof OPTIONS[number]} */
let v = 'four'; 
//  ^ error: Type '"four"' is not assignable to type '"one" | "two" | "three" | 

Run Code Online (Sandbox Code Playgroud)