Lesson 110 of 296
Constraints, defaults, keyof and indexed access
What you will learn
- Limiting generics with
extends - Default type parameters
keyof- Indexed access types
T[K] typeofin type positions- A typed getProperty function
On this page
Constraints with extends
Sometimes a generic must have certain properties. T extends X means "T can be any type, as long as it fits X".
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest("apple", "fig"); fine: strings have length
longest([1, 2], [1, 2, 3]); fine: arrays have length
longest(10, 20); Error: number has no lengthWithout the constraint, a.length would be an error, because T could be anything.
function getId<T extends { id: string }>(item: T): string {
return item.id;
}Default type parameters
type ApiResponse<T = unknown> = { data: T };
const r: ApiResponse = { data: 1 }; T is unknown
const u: ApiResponse<User> = { data: user };keyof
keyof T gives a union of the property names of T:
type User = { id: number; name: string; email: string };
type UserKey = keyof User; "id" | "name" | "email"Indexed access types
T[K] gives the type of a property:
type UserName = User["name"]; string
type IdOrName = User["id" | "name"]; number | string
type AnyValue = User[keyof User]; number | stringFor arrays, T[number] gives the item type:
type Roles = ["admin", "editor"];
type Role = Roles[number]; "admin" | "editor"A typed getProperty
A task from the study plan:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user: User = { id: 1, name: "Sam", email: "sam@example.com" };
const name = getProperty(user, "name"); name: string
const id = getProperty(user, "id"); id: number
getProperty(user, "age"); Error: "age" is not a key of UserHow it works:
K extends keyof T: the key must be one of T's property names.- The return type
T[K]is the type of that exact property, so the result keeps its precise type.
This pattern appears everywhere: sorting by a key, picking fields, form libraries.
function sortBy<T, K extends keyof T>(items: T[], key: K): T[] {
return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0));
}
sortBy(users, "name");typeof in types
In a type position, typeof gets the type of a value:
const config = { apiUrl: "/api", retries: 3 };
type Config = typeof config; { apiUrl: string; retries: number }Combined with keyof:
type ConfigKey = keyof typeof config; "apiUrl" | "retries"This lets you write data once and get the type from it, instead of writing both.
Common mistakes
- Forgetting the constraint, then getting errors when using properties of T.
- Writing
key: stringinstead ofK extends keyof T, which loses type safety. - Confusing JavaScript's runtime
typeofwith type-leveltypeof.
How to say it in an interview
"Constraints with extends limit what a type parameter can be, so I can safely use its properties. keyof produces the union of a type's keys, and indexed access T of K gives the type of a property. Combining them, getProperty with K extends keyof T returning T of K only accepts real keys and returns the exact property type. Type-level typeof lets me derive types from values, such as keyof typeof config."
Key words
| Word | Meaning |
|---|---|
| Constraint | T extends X: limits what T can be |
| Default type parameter | A type used when none is given |
| keyof | The union of a type's property names |
| Indexed access type | T[K]: the type of a property |
| Type-level typeof | Getting the type of a value |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.