Why it’s valid to write `typeof someArray[number]` in TypeScript?

  Kiến thức lập trình

Given an interface, we can access its properties of a specific key type:

interface AB {
  a: number;
  b: boolean;
}

type PropertiesByString = AB[keyof AB & string]

This works because keyof AB & string is "a" | "b", which are all valid keys of AB. The same logic doesn’t apply to arrays:

const MyArray = [
  { name: "Alice", age: 15 },
  { name: "Bob", age: 23 },
  { name: "Eve", age: 38 },
];
 
type Person = typeof MyArray[number];

The code is valid, but the number here includes 4 and much more. Why number is allowed here?

LEAVE A COMMENT