Recently, I attempted to verify whether a variable is a custom type made up of different strings. I came across this helpful post Typescript: Check "typeof" against custom type that explains how to create a validator for this specific type.
const fruit = ["apple", "banana", "grape"];
export type Fruit = (typeof fruit)[number];
const isFruit = (x: any): x is Fruit => fruit.includes(x);
One part I'm struggling to understand is this instruction:
(typeof fruit)[number]
Can someone explain how this works? I know that typeof
is Typescript's query type, but the [number]
part is confusing to me. It's meant to "define your Fruit type in terms of an existing array of literal values."