241 cards
A generic in TypeScript is a placeholder for a type that is filled in at the call site, letting a single function, class, or interface operate over many types while preserving the relationships between inputs and outputs. The simplest form is a generic function such as function identity<T>(x: T): T { return x; },...
TypeScript ships a rich set of utility types that compose new shapes from existing ones. The companions of Partial<T> are Required<T>—implemented as { [K in keyof T]-?: T[K] }—and Readonly<T>, each applying a single modifier to every property. To go deeper, a hand-rolled DeepReadonly<T> = { read...
A conditional type has the shape T extends U ? A : B and is evaluated at the type level: if the source type is assignable to the target, you get A; otherwise B. The most consequential behavior is distribution: a naked type parameter on the left of extends distributes the conditional across every member of a union, so (...
A mapped type walks the keys of an existing type and produces a new one, in the form { [K in keyof T]: ... }. The built-ins Partial<T>, Required<T>, and Readonly<T> are all mapped types, optionally combined with the ? or readonly modifier (or its negation -? / -readonly). Key remapping with as in the...
TypeScript narrows a value's type within control-flow branches using predicates and operators. A user-defined type guard has the form function isString(x: unknown): x is string { return typeof x === 'string'; }, and after if (isString(x)) the variable x is known to be a string. An assertion function—function assertStri...
Tuples let generic types represent fixed-shape arrays precisely, and TypeScript extends this idea with variadic tuple types—tuples containing rest elements like [string, ...number[], boolean]. The simplest operations use rest inference: type First<T extends any[]> = T extends [infer F, ...any[]] ? F : never and t...
Several language features elevate generics from "type-safe containers" into full API design tools. The satisfies operator validates that a value conforms to a shape without forcing it to that shape, so const config = { a: 1 } satisfies Record<string, number> keeps the literal 1 in the inferred type of config whil...