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"