Types in TypeScript
Powerful composition with unions, intersections, mapped and conditional types.
Type aliases
type Point = { x: number; y: number };
Unions and intersections
type Status = "idle" | "loading" | "error";
type WithId = { id: string } & { createdAt: Date };
keyof and typeof
interface User { id: number; name: string }
type UserKey = keyof User; // "id" | "name"
const DEFAULTS = { retries: 3, cache: true };
type Defaults = typeof DEFAULTS; // { retries: number; cache: boolean }
Indexed access and lookups
type Name = User["name"]; // string
Mapped types
type ReadonlyDeep<T> = {
readonly [K in keyof T]: T[K] extends object ? ReadonlyDeep<T[K]> : T[K]
};
type PartialBy<T, K extends keyof T> = Omit<T, K> & { [P in K]?: T[P] };
Conditional types
type Awaited<T> = T extends Promise<infer U> ? U : T;
type NonNullable<T> = T extends null | undefined ? never : T;
Distributivity: T extends U ? X : Y distributes over unions when T is a naked type parameter.
Narrowing helpers
function isOk<T, E>(r: { ok: true; value: T } | { ok: false; error: E }): r is { ok: true; value: T } {
return (r as any).ok === true;
}
Template literal types
type Event = `on${"Click" | "Hover"}`; // "onClick" | "onHover"
Summary
- Compose shapes with unions/intersections
- Use mapped and conditional types to transform types
- Apply
inferto extract parts of complex types