Sub topic 2
Looking up property types with `T[K]`
Assume you know interfaces, union types, JavaScript objects, and basic generics. Indexed access types let you look up a property type from another type.
Indexed access types: `T[K]`
T[K] means “the type of property K in type T.” The key must be a valid property name. If K is a union, T[K] becomes a union of the matching property types.
interface User {
id: number;
name: string;
email?: string;
}
type Id = User["id"]; // number
type NameOrId = User["name" | "id"]; // string | number
type AnyValue = User[keyof User]; // string | number | undefined
function printValue(user: User, key: keyof User): void {
console.log(user[key]);
}Because email is optional, User["email"] includes undefined when strict null checking is enabled.
Preserving literals with `as const`
TypeScript often widens a mutable array’s elements to string. The as const assertion preserves each value as a string literal and makes the array readonly.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
console.log(isRole("editor")); // trueWithout as const, the array is usually string[], so its element type is only string. The literal union "admin" | "editor" | "viewer" would be lost.
Array and tuple element types with `T[number]`
For an array or tuple type, number means any numeric index. Therefore, T[number] produces the union of all element types.
For example, typeof ROLES is a readonly tuple. Indexing it with number gives the union of its three literal elements. This pattern keeps runtime data and its type definition together.
Exercise
What is the type of type Value = [string, number, boolean][number]?
Show answer
string | number | boolean, because number selects any position in the tuple.