Sub topic 5
Looking up property types with T[K]
Assume you know TypeScript interfaces, type aliases, union types, arrays, functions, and basic generics. This chapter uses those ideas to inspect an existing type instead of repeating its property types manually.
An indexed access type looks up a property type from another type. Its syntax is T[K]:
Tis the type being inspected.Kis a property key, such as"name".- The result is the type stored at that key.
This is similar to reading user["name"] at runtime, but TypeScript performs the lookup while checking types.
Looking up one property
Given an object type, place a string literal key inside brackets:
interface User {
id: number;
name: string;
email?: string;
}
type IdType = User["id"]; // number
type NameType = User["name"]; // string
type EmailType = User["email"]; // string | undefinedEmailType includes undefined because email is optional. An optional property might be absent when the program runs.
The key must be valid for the type. User["age"] causes a compile-time error because age is not a property of User.
Looking up several properties
The key can be a union of string literal types. TypeScript looks up each property and combines the results into a union:
interface User {
id: number;
name: string;
email?: string;
}
type NameOrId = User["name" | "id"]; // string | number
type AnyValue = User[keyof User]; // string | number | undefinedkeyof User produces "id" | "name" | "email". Therefore, User[keyof User] means “the type of any property in User.” The result is the union of all property types.
This pattern is useful when a function accepts any value from an object:
function printValue(value: User[keyof User]): void {
console.log(value);
}
printValue(42);
printValue("Ada");
printValue(undefined);Because the parameter is a union, the function must handle every possible property type safely.
Indexed access with generic keys
Indexed access types become especially useful with generics. A generic type parameter represents a type chosen by the caller. Constrain a key parameter with keyof:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProperty(user, "name"); // string
const id = getProperty(user, "id"); // number
// getProperty(user, "age"); // ErrorK extends keyof T means that K must be one of the keys in T. The return type T[K] then connects the selected key to the selected property type.
When the caller passes "name", TypeScript infers K as "name", so the result is string. When the caller passes "id", the result is number. Without T[K], the function would lose this relationship and might return a less precise union.
Arrays and tuples with T[number]
An array type can also be indexed. Using number means any valid numeric index:
type Scores = number[];
type Score = Scores[number]; // numberFor a tuple, which is an array with fixed positions and types, T[number] produces a union of its element types:
type Result = [number, string, boolean];
type ResultPart = Result[number]; // number | string | booleanThis technique is often combined with as const to derive a union from one runtime list:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"The as const assertion preserves each array element as a literal type. Without it, the array would usually become string[], and indexing it with number would produce only string.
Common errors
- Writing
T[K]whenKis not constrained tokeyof T. - Forgetting that optional properties include
undefined. - Expecting
User[keyof User]to preserve the property name. It produces only a union of values. - Omitting
as constwhen a literal union is required from an array.
Exercise
What is the type of Product[keyof Product] for interface Product { sku: string; price: number; inStock?: boolean }?
Show answer
string | number | boolean | undefined, because it is the union of all property types, including undefined for the optional property.