Readonly, Record, Extract, and Exclude
Readonly<T> makes properties readonly at the type level. Record<K, V> constructs a key/value object. Extract<T, U> keeps union members assignable to U, while Exclude<T, U> removes them. NonNullable<T> removes null and undefined; ReturnType<F> obtains a function's return type.
These tools become easier when you think in terms of unions and transformations. They do not inspect runtime values. For complex public types, consider naming intermediate types so errors and editor tooltips remain understandable.
Transform a union
type Status = "queued" | "running" | "done" | "failed";
type FinishedStatus = Extract<Status, "done" | "failed">;
type ActiveStatus = Exclude<Status, "done" | "failed">;
type MaybeUser = { id: string } | null | undefined;
type UserOnly = NonNullable<MaybeUser>;💡
Extract selects the matching union members; Exclude removes matching members; NonNullable removes nullish members.Key Takeaways
- Extract filters a union by assignability.
- Exclude removes union members assignable to a target.
- NonNullable removes null and undefined from a type.
Knowledge Check
What is `Exclude<"a" | "b" | "c", "b">`?