How do you get the element type of an array type or a tuple in TypeScript?
Use an indexed access with number: T[number]. For string[] it gives string, and for a readonly tuple declared as const it gives the union of its member literals.
Explain it simply
An array type says "a list of something". To get that "something" you ask for the type at any numeric index: T[number].
Combine this with as const and a list of strings turns into a type with exactly those strings. One list then serves both the runtime loop and the type.
Example
type Marks = number[];
type Mark = Marks[number]; // number
const cities = ["Pune", "Delhi", "Patna"] as const;
type City = (typeof cities)[number]; // "Pune" | "Delhi" | "Patna"
function isCity(x: string): x is City {
return (cities as readonly string[]).includes(x);
}
for (const c of cities) {
console.log(c); // runtime use of the same list
}
const pair = [1, "a"] as const;
type Pair0 = (typeof pair)[0]; // 1
type PairAny = (typeof pair)[number]; // 1 | "a"What to say in the interview
"T[number] is the element type of any array-like type. With a const-asserted array, (typeof list)[number] gives the union of its literal members, so one array drives both runtime values and the type, without an enum."