我最近尝试检查变量是否为自定义类型(在我的情况下,它包含几个不同的字符串)。 我发现了另一则帖子Typescript: Check "typeof" against custom type 确切讨论了如何为这种类型的验证器。
const fruit = ["apple", "banana", "grape"];
export type Fruit = (typeof fruit)[number];
const isFruit = (x: any): x is Fruit => fruit.includes(x);
但是,我正在努力理解以下说明:
(typeof fruit)[number]
它如何工作?我知道typeof
是Typescript's query type,但我真的不明白[number]
的含义。
应该是“ 根据现有的文字值数组定义您的Fruit类型”
答案 0 :(得分:1)
如果您查看typeof fruit
的类型,则会得到:type AllFruit = ['apple', 'banana', 'grape'];
。
您可能需要制作数组
readonly
以获得此结果 (即const fruit = <const>['apple', 'banana', 'grape'];
)。
然后您可以为该类型编制索引:
type Apple = AllFruit[0]; // 'apple'
type Grape = AllFruit[2]; // 'grape'
type AppleGrape = AllFruit[0 | 2]; // 'apple' | 'grape'
因此[number]
几乎只是索引数组中的每个值:
type Fruit = typeof fruit[0 | 1 | 2]; // 'apple' | 'banana' | 'grape'
type Fruit = typeof fruit[number]; // 'apple' | 'banana' | 'grape'
希望有帮助。