Generics are how TypeScript lets a function or type work with many types while still remembering which one it was given. They are also where a lot of TypeScript code gets harder to read than it needs to be. Angle brackets pile up, type parameters get names like T, U and V, and it becomes unclear what any of it buys you.

This article is for developers who can read basic generic code but want to write it with confidence. We will start with why generics exist, then cover inference, constraints, defaults, and two newer tools: const type parameters and the NoInfer utility type. Along the way we will look at the mistakes that make generic code worse rather than better.

Why generics exist

#

Take a function that returns the first item of an array. Without generics, you have to choose between being too specific and losing information.


_10
function firstNumber(items: number[]): number | undefined {
_10
return items[0];
_10
}
_10
_10
function firstAnything(items: unknown[]): unknown {
_10
return items[0];
_10
}
_10
_10
const a = firstAnything(["a", "b"]); // unknown, so a.toUpperCase() fails

A type parameter connects the input to the output.


_10
function first<T>(items: T[]): T | undefined {
_10
return items[0];
_10
}
_10
_10
const name = first(["Ada", "Grace"]); // string | undefined
_10
const id = first([1, 2, 3]); // number | undefined

That connection is the whole point. A generic is useful when a type appears in more than one place and those places must agree: a parameter and the return type, two parameters, or a property and a method.

Let inference do the work

#

You rarely need to write type arguments at the call site. TypeScript infers T from the arguments you pass, which is what happened with first above. Writing first<string>(["Ada"]) is allowed but adds nothing.

There are a few cases where explicit type arguments are the right call:


_10
// Nothing to infer from, so you say what will go in later
_10
const cache = new Map<string, number>();
_10
_10
// The initial value is narrower than the values you will store
_10
const [user, setUser] = useState<User | null>(null);
_10
_10
// A function whose type parameter only appears in the return type
_10
const config = JSON.parse(raw) as AppConfig; // see the note on this below

The rule is simple: if TypeScript can work it out from the values, let it. If the values do not carry enough information, pass the type explicitly.

Constraints with extends

#

An unconstrained T could be anything, so you cannot do much with it inside the function. A constraint tells TypeScript the minimum shape T must have.


_10
function longest<T extends { length: number }>(a: T, b: T): T {
_10
return a.length >= b.length ? a : b;
_10
}
_10
_10
longest("apple", "fig"); // string
_10
longest([1, 2, 3], [4]); // number[]
_10
longest(10, 20);
_10
// Error: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

The return type is still the specific T you passed in, not { length: number }. That is what separates a constrained generic from a function that just takes the constraint type as a parameter.

Constraining one parameter by another

The most common real-world constraint uses keyof so that a key must belong to an object.


_10
function pick<T, K extends keyof T>(obj: T, key: K): T[K] {
_10
return obj[key];
_10
}
_10
_10
const post = { id: 42, title: "Generics", published: false };
_10
_10
const title = pick(post, "title"); // string
_10
const published = pick(post, "published"); // boolean
_10
pick(post, "author");
_10
// Error: Argument of type '"author"' is not assignable to parameter of type '"id" | "title" | "published"'.

T[K] is an indexed access type. It gives you the type of the property at that key, so the return type changes depending on which key you pass.

Default type parameters

#

Type parameters can have defaults, just like function parameters. This is most useful on generic types where the common case should not need extra typing.


_10
type ApiResponse<TData = unknown, TError = { message: string }> =
_10
| { ok: true; data: TData }
_10
| { ok: false; error: TError };
_10
_10
const raw: ApiResponse = await getSomething(); // data is unknown
_10
const users: ApiResponse<User[]> = await getUsers(); // data is User[]

Defaults must come after any required type parameters, and a default must satisfy its own constraint if it has one.

const type parameters

#

By default, TypeScript widens literal values when it infers a type parameter. An array of strings becomes string[], not a tuple of the exact strings.


_10
function defineRoutes<T extends readonly string[]>(paths: T): T {
_10
return paths;
_10
}
_10
_10
const routes = defineRoutes(["/", "/about"]);
_10
// string[]

Before TypeScript 5.0, callers had to write as const at every call site to keep the literals. Now the function author can ask for that behaviour by adding the const modifier to the type parameter.


_10
function defineRoutes<const T extends readonly string[]>(paths: T): T {
_10
return paths;
_10
}
_10
_10
const routes = defineRoutes(["/", "/about"]);
_10
// readonly ["/", "/about"]
_10
_10
type Route = (typeof routes)[number];
_10
// "/" | "/about"

Note the readonly in the constraint. If the constraint is a mutable string[], TypeScript cannot infer a read-only tuple that fits it, and it falls back to string[]. The const modifier only affects inference from literals written directly in the call. If you pass a variable that was declared earlier, its type has already been widened.

NoInfer: stop a parameter from widening T

#

Sometimes one argument should decide what T is, and another argument should only be checked against it. Without help, TypeScript considers every argument when inferring.


_10
function createSelect<T extends string>(options: T[], initial?: T) {
_10
// ...
_10
}
_10
_10
createSelect(["small", "medium", "large"], "extra-large");
_10
// No error: T was inferred as "small" | "medium" | "large" | "extra-large"

TypeScript 5.4 added the NoInfer utility type. Wrapping a parameter's type in it tells the compiler not to use that argument for inference.


_10
function createSelect<T extends string>(options: T[], initial?: NoInfer<T>) {
_10
// ...
_10
}
_10
_10
createSelect(["small", "medium", "large"], "extra-large");
_10
// Error: Argument of type '"extra-large"' is not assignable to parameter of type '"small" | "medium" | "large"'.

Now options alone decides T, and initial must be one of those options.

A generic type in practice: Result

#

Generics combine well with discriminated unions. A Result type makes success and failure explicit without throwing.


_19
type Result<T, E = Error> =
_19
| { ok: true; value: T }
_19
| { ok: false; error: E };
_19
_19
async function tryCatch<T>(promise: Promise<T>): Promise<Result<T>> {
_19
try {
_19
return { ok: true, value: await promise };
_19
} catch (err) {
_19
return { ok: false, error: err instanceof Error ? err : new Error(String(err)) };
_19
}
_19
}
_19
_19
const result = await tryCatch(fetch("/api/user").then((r) => r.json()));
_19
_19
if (result.ok) {
_19
console.log(result.value);
_19
} else {
_19
console.error(result.error.message);
_19
}

The type parameter flows from the promise you pass in to the value you read out, and checking result.ok narrows the union.

Common mistakes

#

A type parameter that appears only once

The TypeScript handbook puts it well: type parameters should appear twice. If T appears only in the return type, it is a type assertion in disguise.


_10
// Looks safe, but the caller picks T and nothing checks it
_10
async function getJson<T>(url: string): Promise<T> {
_10
const res = await fetch(url);
_10
return res.json();
_10
}
_10
_10
const user = await getJson<User>("/api/user"); // trusted, not checked

This is no safer than writing as User. If you want the type to be earned, take a parser so that the type comes from a real check.


_10
async function getJson<T>(url: string, parse: (data: unknown) => T): Promise<T> {
_10
const res = await fetch(url);
_10
return parse(await res.json());
_10
}

Now T appears twice, and it is inferred from whatever parse returns. A schema library's parse function slots straight in.

Returning a value that only fits the constraint


_10
function emptyOf<T extends string>(): T {
_10
return "";
_10
// Error: Type '""' is not assignable to type 'T'.
_10
// '""' is assignable to the constraint of type 'T', but 'T' could be
_10
// instantiated with a different subtype of constraint 'string'.
_10
}

The caller could ask for T to be "yes" | "no", and an empty string is neither. If you see this error, the fix is usually to return the constraint type instead of T.

Generics where a union would do


_10
// Unnecessary
_10
function format<T extends string | number>(value: T): string {
_10
return String(value);
_10
}
_10
_10
// Clearer
_10
function format(value: string | number): string {
_10
return String(value);
_10
}

If the type parameter does not connect anything, drop it.

Names that say nothing

Single letters are fine for a single, obvious parameter. Once you have two or three, descriptive names such as TData, TKey and TError make error messages and hover tooltips much easier to read.

Version support

#

Generics, constraints and defaults have been part of TypeScript for many years. The const modifier on type parameters needs TypeScript 5.0 or later, and NoInfer needs 5.4 or later. Everything in this article is type-level only, so it is removed by type-stripping tools such as esbuild, SWC and Node's built-in TypeScript support, and it is allowed under erasableSyntaxOnly.

When not to use it

#
  • When nothing needs to be connected. If a type appears in one place only, use a concrete type or a union.
  • To avoid validating data. A generic return type on a fetch helper does not check anything. Validate at the boundary instead.
  • When the signature becomes the documentation problem. If a function needs four type parameters and conditional types to describe it, consider splitting it into simpler functions or using overloads.
  • For application code that only ever handles one type. Generics pay off in shared utilities, data structures and libraries. In a single component or route handler, concrete types are often easier to follow.

Wrapping up

#
  • A generic is worth it when a type must match in two or more places, such as an argument and a return value.
  • Let inference supply type arguments, and only write them when the values cannot.
  • Use extends to require a minimum shape, and K extends keyof T to tie keys to objects.
  • const type parameters keep literal types without as const at every call, and NoInfer stops a secondary argument from widening T.
  • A type parameter that appears only in the return type is an unchecked assertion, so take a parser instead.
file under:
Typescript

Was this article helpful?

About the author

Danny Engineering

A software engineer with a strong belief in human-centric design and driven by a deep empathy for users. Combining the latest technology with human values to build a better, more connected world.