Generic (TypeScript)

A generic is a type that takes another type as a parameter, written in angle brackets like `Array<string>`. Generics let you write reusable code that works with many types while staying type-safe.

TypeScript

Without generics you would either repeat a function for every type or fall back to `any` and lose type safety. A generic captures the caller's type in a placeholder (often `T`) and reuses it throughout.

When you call a generic function, TypeScript usually infers the type argument from what you pass in, so you rarely have to write the angle brackets yourself.

Syntax

function f<T>(arg: T): T { ... }

Examples

TypeScript

function first<T>(items: T[]): T {
  return items[0];
}

const n = first([1, 2, 3]); // n: number
const s = first(["a", "b"]); // s: string
console.log(n, s);

Output:

1 a

Learn it in a lesson

See also

Back to the Dictionary