0

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"

2
  • is it [number] or is there an actual numeric, e.g., [3]? Commented Jan 8, 2020 at 7:39
  • it is [number] . Commented Jan 8, 2020 at 7:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.