Sub topic 3
Type-Safe Property Access with `K extends keyof T`
Assume you know interfaces, union types, JavaScript objects, and basic generics. This chapter focuses on using existing types and values to keep property access type-safe.
Type-safe property access with `K extends keyof T`
keyof T produces a union of the property names in T. A generic key parameter constrained with extends can therefore accept only valid keys.
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"); // ErrorT[K] is an indexed access type. It looks up the property type selected by K. The compiler keeps the connection between the argument and the return type.
Building mapped types with `keyof`
A mapped type loops over the keys of a type. This example adds null to every property while preserving each property's original type.
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
interface Point {
x: number;
y: number;
}
type NullablePoint = Nullable<Point>;
// { x: number | null; y: number | null }Using `typeof` with functions
In a type position, typeof obtains the type of a value. Utility types can then inspect a function's return type and parameter tuple.
function createUser(name: string) {
return { id: 1, name };
}
type NewUser = ReturnType<typeof createUser>;
type CreateUserArgs = Parameters<typeof createUser>;
// NewUser: { id: number; name: string }
// CreateUserArgs: [name: string]How `keyof` treats index signatures
An index signature describes properties whose names are not known individually. For a string index signature, keyof is string | number because JavaScript converts numeric property access to strings.
| Type | Result of `keyof` | Column |
|---|---|---|
| `{ [key: string]: boolean }` | `string \ | number` |
Unions, intersections, and optional properties
For a union, keyof keeps keys safe for every possible member. For an intersection, it combines the keys.
type A = { a: number; shared: string };
type B = { b: boolean; shared: string };
type UnionKeys = keyof (A | B); // "shared"
type AllKeys = keyof (A & B); // "a" | "b" | "shared"
interface Profile {
email?: string;
}
type Email = Profile["email"]; // string | undefinedAn optional property includes undefined when strictNullChecks is enabled.
Exercise
What is the return type of getProperty({ active: true }, "active")?
Show answer
boolean, because K is "active" and T[K] looks up the active property's type.