Reputation: 11888
I've recently tried to check if a variable is of a custom type (which consists in my case of several different strings). I found this other post Typescript: Check "typeof" against custom type which discusses exactly how to do a validator for this kind of type.
const fruit = ["apple", "banana", "grape"];
export type Fruit = (typeof fruit)[number];
const isFruit = (x: any): x is Fruit => fruit.includes(x);
I am however struggling to apprehend this instruction:
(typeof fruit)[number]
How does it work? I understand that typeof
is Typescript's query type but I really don't get what the [number]
means.
It is supposed to "define your Fruit type in terms of an existing array of literal values"
Upvotes: 0
Views: 458
Reputation: 54
If you look at the type for typeof fruit
you get: type AllFruit = ['apple', 'banana', 'grape'];
.
You might need to make the array
readonly
to get this result (i.e.const fruit = <const>['apple', 'banana', 'grape'];
).
You can then index this type:
type Apple = AllFruit[0]; // 'apple'
type Grape = AllFruit[2]; // 'grape'
type AppleGrape = AllFruit[0 | 2]; // 'apple' | 'grape'
So the [number]
is pretty much just indexing every value in the array:
type Fruit = typeof fruit[0 | 1 | 2]; // 'apple' | 'banana' | 'grape'
type Fruit = typeof fruit[number]; // 'apple' | 'banana' | 'grape'
Hope that helps.
Upvotes: 1