Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 96 ยท Generics

Generics

Learn TypeScript generics from scratch - why they beat any, generic functions, type argument inference, multiple type parameters, generic arrow functions and when not to use them.

Some functions don't care what kind of value they handle. Taking the first item of an array, wrapping a value in an object, caching a result or grouping a list works the same way for numbers, strings and users. But you still want the result to have a precise type: the first item of a string[] should be a string, not "something".

Generics solve exactly that. A generic function has type parameters: placeholders for types that get filled in each time the function is called, usually by inference, so you rarely write them out. They're how Array<T>, Promise<T>, Map<K, V> and almost every library type are built. This lesson covers generic functions; the next two cover constraints and defaults and generic interfaces, classes and types.

The problem generics solve

Here's a function that returns the first element of an array, written three ways without generics:

TypeScript Three ways to lose type information (crashes on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The run crashes with TypeError: a.toFixed is not a function, and TypeScript didn't warn you, because any switches type checking off (any, unknown, never and void explains why that's so dangerous). Version 2 is safe but clumsy, and version 3 means writing firstNumber, firstUser and so on forever.

A generic version gets the best of all three:

TypeScript Your first generic function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

<T> after the function name declares a type parameter called T. Inside the signature, T is used like any other type: the parameter is a read-only array of T, and the result is T | undefined. Each call binds T to a concrete type. For ['ada', 'grace'], TypeScript sees a string[] and binds T to string, so name gets the type string | undefined and toUpperCase() is allowed (after the ?., because the array might be empty).

The T | undefined is honest: an empty array has no first element. With noUncheckedIndexedAccess, items[0] would already have that type on its own (The tsconfig.json File covers the option).

T is a convention, not a keyword. Single capital letters are common for short, obvious roles: T for "type", U for a second type, K and V for keys and values, E for errors. For longer signatures, descriptive names such as TItem or Item make code easier to read.

Type argument inference

You almost never write type arguments yourself. TypeScript infers them from the arguments, much like it infers variable types from initializers. When it infers a type you don't want, or there's nothing to infer from (like the empty array above), pass the type argument explicitly in angle brackets.

Inference also explains this classic error. When one type parameter appears in several places, TypeScript picks a candidate from the first argument and then checks the rest against it:

TypeScript One T, two different arguments (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(7,21): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

The third call binds T to number from the 1, then rejects 'one'. That's usually what you want: comparing a number with a string is almost always a bug. If mixing really is intended, say so with an explicit union: same<number | string>(1, 'one') compiles.

Inference keeps literal types when it can

Type parameters are inferred as precisely as the arguments allow. With a plain T, a string literal argument produces a literal type, and the usual const/let widening rules apply to the result:

TypeScript What exactly gets inferred

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The assignment to direction is a compile-time proof: if exact were a plain string, that line would fail. Object properties are widened (x: number, not x: 1), as they would be in an ordinary const declaration. When you want literal types preserved deeply, const type parameters do it.

Multiple type parameters

A function can have as many type parameters as it needs, separated by commas. They're most useful when they describe a relationship between inputs and outputs:

TypeScript map, zip and groupBy with several type parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at how mapAll infers both parameters. T comes from words (string). Then TypeScript knows the callback's item is a string (that's contextual typing), and U is inferred from what the callback returns. In groupBy, K is inferred from the key callback: w[0] is a string, so the result is a Map<string, string[]>. (With noUncheckedIndexedAccess turned on, w[0] and left[i] would include undefined, and zip would need ! non-null assertions, safe here because i never passes the shorter array.)

JavaScript now has Map.groupBy() and Object.groupBy() built in (ES2024), and their TypeScript types are generic in exactly this way. Writing your own version is still the best way to understand how such types work.

Generic arrow functions and function types

Arrow functions take type parameters before the parameter list:

TypeScript Generic arrows and generic function types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice the difference between Picker and PickerOf<T>. In Picker, the type parameter sits on the call signature, so a Picker works for any element type on every call. In PickerOf<T>, it sits on the alias, so you choose T once (PickerOf<number>) and get a function that only takes number arrays. Both are useful; Generic Interfaces, Classes and Types goes deeper.

logged uses a rest-tuple type parameter, Args extends unknown[], to capture an entire parameter list. That extends is a constraint, the topic of the next lesson.

In .tsx files, <T>(x: T) => x is ambiguous, because <T> looks like a JSX tag. Write <T,>(x: T) => x (with a trailing comma) or <T extends unknown>(x: T) => x there. In plain .ts files, like our editor's, <T> is fine.

Generics you already use

Most built-in types you've met are generic. When TypeScript can't infer the type argument, typically because a collection starts empty, provide it explicitly:

TypeScript Built-in generic types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

That last Map is a quiet trap: new Map() without arguments or a type annotation becomes Map<any, any>, and nothing you put in or take out is checked. Always give empty collections a type argument (or an annotated variable). The example also uses top-level await, which works because our editor runs code as an ES module.

When not to use generics

Generics are for connecting types. A good rule of thumb: a type parameter should appear at least twice in a signature, for example once in a parameter and once in the return type. If it appears only once, it isn't relating anything and can usually be replaced by a plain type:

TypeScript
// Unnecessary: T is used only once
function countItems<T>(items: readonly T[]): number {
  return items.length;
}

// Simpler and just as safe
function countItemsSimple(items: readonly unknown[]): number {
  return items.length;
}

// Worse: a generic return type nobody can check. The caller picks T,
// but the function has no way to produce a real T. This is a disguised cast.
function parseJson<T>(text: string): T {
  return JSON.parse(text);
}

The parseJson<T> pattern is common and risky: parseJson<User>(text) looks type-safe, but nothing verifies that the text describes a User. Return unknown instead and validate it, as shown in Custom Type Guards.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given function first<T>(items: readonly T[]): T | undefined, what is the type of first([true, false])?

    T is inferred from the array type boolean[], so the result is boolean | undefined.
  2. 2. Does same(1, 'one') compile, where function same<T>(a: T, b: T): boolean?

    TypeScript infers number from the first argument and reports TS2345 for the string. Write same<number | string>(1, 'one') if mixing is intended.
  3. 3. What is the difference between type A = <T>(x: T) => T and type B<T> = (x: T) => T?

    In A the type parameter belongs to the call signature, so each call chooses T. In B it belongs to the alias, so B<number> only accepts and returns numbers.
  4. 4. Why is const cache = new Map(); a problem in strict TypeScript?

    With no arguments to infer from and no annotation, Map's type parameters fall back to any. Write new Map<string, number>() instead.
  5. 5. Which signature uses its type parameter in a pointless way?

    In size, T appears only once and relates nothing. readonly unknown[] says the same thing more simply.

Summary

  • A generic function declares type parameters in angle brackets (<T>) and uses them in its parameter and return types, so the output type follows the input type.
  • TypeScript infers type arguments from the arguments; write them explicitly (first<Date>([])) when there's nothing to infer from or the inference isn't what you want.
  • A type parameter used in several places is inferred from the first candidate, which is why same(1, 'one') fails.
  • Use several type parameters to describe relationships (mapAll<T, U>, zip<A, B>, groupBy<T, K>).
  • Arrow functions, object methods and function types can be generic. A type parameter on a call signature is chosen per call; one on an alias is fixed when the alias is used.
  • Give empty collections a type argument, and avoid type parameters that appear only once or that just disguise a cast.

Next: Generic Constraints and Defaults