function <T> Generic Functions
Last updated: 2026-10-22
function <T> Generic Functions
Generic functions use a type parameter <T> to turn "types" into arguments: one piece of logic works for many types while input and output types stay linked. Safer than any (type info is preserved) and cheaper than copy-pasting per-type versions.
| Group | Generics |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
function identity<T>(value: T): T {
return value;
}
// Multiple type parameters + constraints
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
⚙️ Parameters
| <T> | Inferred from arguments or given explicitly; conventions: T/U/V for general types, K for keys, E for elements |
|---|---|
| K extends keyof T | Constraint: K must be a key of T; invalid keys are compile errors |
Returns:Expressed via type parameters — the return can share the argument's type (T) or be derived (Pick<T, K>).
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
{"id":1,"name":"Charlie"}
(Runtime output after transpilation; passing "age" in keys is a type error — K is constrained by keyof T)
💡 Notes
ℹ️ Info Generics are fully erased after transpilation — there is no T at runtime, just a plain function; all type linkage happens at compile time.
💡 Tip Prefer expressing return types via type parameters (e.g. Pick<T, K>) instead of a loose hand-written type — callers get the precise, linked type.
⚠️ Note More generics is not better: if a single type suffices, adding T only hurts readability; write the concrete version first, generalize when duplication appears.
🏷️ Related Generics
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Generics vs any — what's the difference?
A any erases type info (argument and return become disconnected, no further checking); generics keep the linkage (identity(42) returns number). Generics are the safe alternative to any.
Q When should a function be generic?
A When argument and return types are linked, or one logic must serve many types. Signals: you are about to write any, or copy-pasting the same function for different types.
Q How do I read <T, K extends keyof T>?
A Two type parameters: T is any type; K must be one of T's keys (constrained by keyof T). For pick(user, ["id"]): T = typeof user, K = "id", and the return type is { id: number }.