Sub topic 7
Array and Tuple Element Types with T[number]
This chapter assumes you have read the earlier chapters on keyof, typeof in type positions, and indexed access types (T[K]). You should also be comfortable with as const and with generic constraints. Here you will use one specific indexed access, T[number]. It turns an array or tuple type into the type of its elements.
Why indexing with number works
An indexed access type looks up a property type by key. Arrays are objects, and their keys are numeric positions. The Array<T> interface declares a numeric index signature, so any number is a valid key and the result is the element type.
type Numbers = number[][number]; // number
type Mixed = (string | number)[][number]; // string | number
type Flags = Array<boolean>[number]; // boolean
type Frozen = readonly string[][number]; // stringIn each case number is a type, not a value. You are saying "the type you get when you index this array with any number". The same rule applies to ReadonlyArray<T>, which also has a numeric index signature.
Tuples: one position or all positions
A tuple is an array type with a fixed length and a known type at each position. You can index a tuple with a literal position, which gives that position's type. You can also index it with number, which gives the union of all element types.
type Pair = [string, number];
type First = Pair[0]; // string
type Second = Pair[1]; // number
type Either = Pair[number]; // string | number
type Both = Pair[0 | 1]; // string | number
// type Third = Pair[2]; // Error: Tuple type '[string, number]' of length '2' has no element at index '2'.A literal index outside the tuple's length is an error. Pair[number] is always allowed because number stands for "some position".
Optional and rest elements follow the same rule: each contributes its type to the union.
type WithOptional = [string, number?];
type OptionalElement = WithOptional[number]; // string | number | undefined
type WithRest = [string, ...boolean[]];
type RestElement = WithRest[number]; // string | booleanAn optional tuple element adds undefined to the union, as an optional property does in User["email"].
Deriving a union from a runtime array
The most common use of T[number] is to keep one list of values as the source of truth for both runtime and compile time. Three steps are involved:
- Declare the array with
as constso its literal values are kept. - Use
typeofto get the array's type. - Index that type with
number.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
console.log(isRole("admin")); // true
console.log(isRole("owner")); // falseAdding "owner" to ROLES updates both the runtime list and the Role type. There is no second place to edit.
Without as const, the array is inferred as string[], and the union collapses to string:
const LOOSE = ["admin", "editor", "viewer"];
type LooseRole = (typeof LOOSE)[number]; // stringThe parentheses in (typeof ROLES)[number] are optional. Writing them makes it clear that typeof applies to ROLES and [number] applies to the result.
Why the includes call needs a cast
ROLES has the type readonly ["admin", "editor", "viewer"]. Its includes method accepts only those three literals, so passing a plain string is an error. Widening the array to readonly string[] lets includes accept any string. The value is Role return type then tells the compiler that a true result narrows value to Role.
Arrays of objects
as const also works on arrays of objects. It makes every property readonly and keeps string and number literals. You can then chain [number] with a property lookup.
const routes = [
{ path: "/", name: "home" },
{ path: "/about", name: "about" },
{ path: "/contact", name: "contact" },
] as const;
type Route = (typeof routes)[number];
// { readonly path: "/"; readonly name: "home" }
// | { readonly path: "/about"; readonly name: "about" }
// | { readonly path: "/contact"; readonly name: "contact" }
type RouteName = (typeof routes)[number]["name"]; // "home" | "about" | "contact"
type RoutePath = Route["path"]; // "/" | "/about" | "/contact"Route is a union of three object types. Indexing a union with "name" looks the property up on each member and unions the results. If you leave out as const, both name and path become plain string.
Elements of values you did not write yourself
Sometimes the array comes from a function, not a literal. Combine ReturnType with [number]. For an async function, wrap the return type in Awaited to unwrap the promise first.
async function fetchUsers() {
return [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
];
}
type FetchResult = ReturnType<typeof fetchUsers>; // Promise<{ id: number; name: string }[]>
type User = Awaited<ReturnType<typeof fetchUsers>>[number]; // { id: number; name: string }If you forget Awaited, then Promise<...>[number] is an error. Promise has no numeric index signature, so number is not a valid key.
A reusable helper and a generic function
You can name the pattern with a type alias. The constraint readonly unknown[] accepts both mutable and readonly arrays and tuples.
type ElementOf<T extends readonly unknown[]> = T[number];
const SIZES = ["s", "m", "l"] as const;
type Size = ElementOf<typeof SIZES>; // "s" | "m" | "l"
type Id = ElementOf<number[]>; // numberThe same constraint works on a function parameter. The return type then follows whatever array the caller passes.
function first<T extends readonly unknown[]>(items: T): T[number] | undefined {
return items[0];
}
const a = first(["x", "y"]); // string | undefined
const b = first(SIZES); // "s" | "m" | "l" | undefined
const c = first([1, 2, 3] as const); // 1 | 2 | 3 | undefinedFor ["x", "y"], TypeScript infers string[], so the result is string | undefined. When the argument already has a readonly tuple type, the literals are kept. For the unconstrained [1, 2, 3] without as const, you would get number | undefined.
Edge cases and common errors
- Empty tuple.
[][number]isnever, because there are no elements to form a union. This is whatas constgives forconst EMPTY = [] as const. - Position is lost.
T[number]forgets order and length.["a", "b"]and["b", "a"]produce the same union. If order matters, use literal indexes such asT[0]. - Readonly mismatch. A
readonlytuple is not assignable to a mutablestring[]. A function that takesstring[]rejectsROLES. Declare such parameters asreadonly string[]. - Objects without a numeric index.
numbercan only index types that have a numeric index signature, plus tuples.{ a: 1 }[number]is an error. - Duplicates collapse. A union has no duplicates.
["a", "a", "b"] as conststill gives"a" | "b". - Union of arrays.
(string[] | number[])[number]isstring | number. The lookup happens on each member and the results are unioned.
The following table compares the lookups you now have available.
| Expression | Applied to | Result | Column | Column |
|---|---|---|---|---|
| `T[number]` | `string[]` | `string` | ||
| `T[number]` | `readonly ["a", "b"]` | `"a" \ | "b"` | |
| `T[0]` | `readonly ["a", "b"]` | `"a"` | ||
| `T[number]` | `[string, number?]` | `string \ | number \ | undefined` |
| `T[number]` | `[]` | `never` | ||
| `T[number]["k"]` | array of objects | union of each object's `k` property type |
Putting it together
The snippet below uses one array to drive a lookup table. The Record type forces the object to have exactly one entry per role, so adding a role without updating the table becomes a compile error.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
const canWrite: Record<Role, boolean> = {
admin: true,
editor: true,
viewer: false,
};
for (const role of ROLES) {
console.log(role, canWrite[role]);
}If you add "owner" to ROLES, TypeScript reports that canWrite is missing the property owner. The loop variable role has type Role, so canWrite[role] is always a valid lookup.
Exercise
Given const LEVELS = ["low", "mid", "high"] as const;, write a type Level that is the union of its values. Then say what Level becomes if you delete as const, and why.
Show answer
type Level = (typeof LEVELS)[number]; gives "low" | "mid" | "high". Without as const, TypeScript infers LEVELS as string[], so Level becomes plain string. The literal values are not preserved, so the union collapses.
Exercise
What are the types of T[number] and T[1] when type T = [boolean, string, number?]? Which one would be an error if you wrote T[3]?
Show answer
T[number] is boolean | string | number | undefined, because the optional element adds undefined. T[1] is string. T[3] is an error, because the tuple has three positions (0, 1 and 2), so there is no element at index 3.
Exercise
Given const items = [{ kind: "a", n: 1 }, { kind: "b", n: 2 }] as const;, write a type for the union of all kind values.
Show answer
type Kind = (typeof items)[number]["kind"]; gives "a" | "b". The [number] lookup produces a union of the two object types, and ["kind"] reads that property from each member.