AceDevHub
Functions & ModelingFree

Generics Fundamentals

Write functions and types that work across types while preserving relationships — constraints, defaults, and the patterns behind Array and Promise.

IntermediateFreeGenerics

Generics parameterize types — one function or interface works for many types while linking inputs and outputs. Without generics you duplicate per-type functions or fall back to any. Array<T>, Promise<T>, and Map<K, V> are built-in generics you already consume daily.

Writing your own unlocks fetch wrappers, cache entries, and shared API envelopes. Constraints with extends limit type parameters to shapes that expose required properties. keyof enables type-safe dynamic property access.

Generic functions

TypeScript infers T from arguments when possible. Explicit <T> helps empty arrays and ambiguous contexts. Multiple type parameters preserve relationships between arguments — pair<A, B> returns [A, B].

generic-fn.ts
Loading editor…

Generic interfaces

ApiResponse<T> wraps any payload with shared metadata. Paginated<T> lists items with page info. Composing generics keeps envelope structure DRY while payload types vary per endpoint.

generic-types.ts
Loading editor…

Constraints with extends

Unconstrained T accepts anything — including types without .length. extends { length: number } guarantees the property exists inside the body. keyof T produces property name unions for safe getters.

constraints.ts
Loading editor…
defaults.ts
Loading editor…
ConceptSyntax
Type parameter<T>
ConstraintT extends U
Default<T = U>
keyofkeyof T

Identity and reusable utilities

identity<T> is the simplest generic — foundation for pipes, caches, and typed storage wrappers. Avoid over-genericizing; if only string and number use a function, a union may be clearer than <T>.

  • Generics link input and output types
  • extends constrains safely
  • keyof for dynamic property reads
  1. 1Generics avoid duplication
  2. 2extends enables property access
  3. 3Defaults simplify APIs
  4. 4Next: tsconfig and compiler options