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.

GroupGenerics
KindSyntax
Strict modeNot 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 TConstraint: 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.
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 }.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏