On this page
Generics, Constraints & Variance
Prev: Structural Typing & Narrowing | Up: type_system | Next: Conditional, Mapped & Template Literal Types
Rel: keyof, NoInfer
Ref: TypeScript Handbook โ Generics
Tags: #public #web #typescript #type-system #generics
Contents
Generic Constraints (extends & keyof)
Constrain generic type parameters with extends to guarantee required properties while preserving exact return types:
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const users = [{ id: 1, name: "Ada" }, { id: 2, name: "Grace" }];
const names = pluck(users, "name"); // string[]
Variance (out Covariant vs. in Contravariant)
- Covariant (
out T): producers/return positions โProducer<Dog>is assignable toProducer<Animal>. - Contravariant (
in T): consumers/parameter positions (understrictFunctionTypes) โHandler<Animal>is assignable toHandler<Dog>. - Invariant (
in out T): mutable read+write containers.
Explicit in/out annotations on generic interfaces speed up type checking and document intent.
Linked from
Related notes
- tuts/typescript/type_system Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/type_system/conditional_and_mapped_types Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/type_system/structural_typing_and_narrowing Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/keyof Linked here; shared tags: #typescript, #web
- tuts/typescript/utility_types/function_and_promise/NoInfer Linked here; shared tags: #typescript, #web
- tuts/typescript shared tags: #typescript, #web
- tuts/typescript/builtins shared tags: #typescript, #web
- tuts/typescript/builtins/any shared tags: #typescript, #web
- tuts/typescript/builtins/as_const shared tags: #typescript, #web
- tuts/typescript/builtins/asserts shared tags: #typescript, #web