Sub topic 1
Reading keys and property types with keyof and T[K]
Prerequisites
This chapter assumes you know basic TypeScript object types, unions, and function types. It also assumes you can write generics with type parameters and constraints, and that you are comfortable with type aliases and interfaces.
keyof and indexed access
keyof T produces a union of the property names of T. An indexed access type T[K] looks up the type of property K in T. Used together, they let you read both the names and the types of an object's properties.
type User = { id: number; name: string };
type UserKeys = keyof User; // "id" | "name"
type NameType = User["name"]; // string
type AllValues = User[keyof User]; // number | stringA common error is indexing with a key that does not exist, such as User["email"]. The compiler rejects it. You can constrain a generic with K extends keyof T so that T[K] is always valid.
Mapped types
A mapped type loops over a union of keys and builds a new property for each one. The syntax [K in keyof T] visits every key, and T[K] reuses that key's original type.
type User = { id: number; name: string };
type MyPartial<T> = { [K in keyof T]?: T[K] };
type PartialUser = MyPartial<User>;
// { id?: number; name?: string }Adding and removing modifiers
Inside a mapped type you can add readonly and ? to each property. A - prefix removes them. A + prefix adds them, which is also what happens when you write no prefix.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Concrete<T> = { [K in keyof T]-?: T[K] };
type Config = { readonly host: string; port?: number };
type MutableConfig = Mutable<Config>;
// { host: string; port?: number }
type ConcreteConfig = Concrete<Config>;
// { readonly host: string; port: number }Each helper changes only the modifier it names. All other parts of the property stay the same.
Homomorphic mapped types
A mapped type of the form { [K in keyof T]: ... } is called homomorphic. When it maps over keyof T directly, TypeScript copies each property's existing readonly and ? modifiers into the result. That is why Mutable above kept port optional. If you map over a plain union of literal keys, the link to T is lost and the modifiers are dropped:
type Config = { readonly host: string; port?: number };
type Copy = { [K in keyof Config]: Config[K] };
// { readonly host: string; port?: number }
type Loose = { [K in "host" | "port"]: Config[K] };
// { host: string; port: number | undefined }Exercise
Write MyRequired<T>, which makes every property required, and give the result for { a?: string; readonly b?: number }.
Show answer
type MyRequired<T> = { [K in keyof T]-?: T[K] }; The result is { a: string; readonly b: number }. The -? removes optionality, and readonly stays on b because the mapped type is homomorphic.