---
title: "TypeScript generics: inference, constraints and const type parameters"
description: "A practical guide to TypeScript generics: letting inference work, adding constraints with extends, defaults, const type parameters, NoInfer, and the common mistakes to avoid."
url: https://www.danny.engineering/article/typescript-generics-inference-constraints-and-const-type-parameters
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:23:00.000Z
tags: ["Typescript"]
---

# TypeScript generics: inference, constraints and const type parameters

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.


```typescript
function firstNumber(items: number[]): number | undefined {
  return items[0];
}

function firstAnything(items: unknown[]): unknown {
  return items[0];
}

const a = firstAnything(["a", "b"]); // unknown, so a.toUpperCase() fails
```


A type parameter connects the input to the output.


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

const name = first(["Ada", "Grace"]); // string | undefined
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:


```typescript
// Nothing to infer from, so you say what will go in later
const cache = new Map<string, number>();

// The initial value is narrower than the values you will store
const [user, setUser] = useState<User | null>(null);

// A function whose type parameter only appears in the return type
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.


```typescript
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

longest("apple", "fig");     // string
longest([1, 2, 3], [4]);     // number[]
longest(10, 20);
// 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.


```typescript
function pick<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const post = { id: 42, title: "Generics", published: false };

const title = pick(post, "title");         // string
const published = pick(post, "published"); // boolean
pick(post, "author");
// 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.


```typescript
type ApiResponse<TData = unknown, TError = { message: string }> =
  | { ok: true; data: TData }
  | { ok: false; error: TError };

const raw: ApiResponse = await getSomething();     // data is unknown
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.


```typescript
function defineRoutes<T extends readonly string[]>(paths: T): T {
  return paths;
}

const routes = defineRoutes(["/", "/about"]);
// 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.


```typescript
function defineRoutes<const T extends readonly string[]>(paths: T): T {
  return paths;
}

const routes = defineRoutes(["/", "/about"]);
// readonly ["/", "/about"]

type Route = (typeof routes)[number];
// "/" | "/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.


```typescript
function createSelect<T extends string>(options: T[], initial?: T) {
  // ...
}

createSelect(["small", "medium", "large"], "extra-large");
// 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.


```typescript
function createSelect<T extends string>(options: T[], initial?: NoInfer<T>) {
  // ...
}

createSelect(["small", "medium", "large"], "extra-large");
// 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.


```typescript
type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

async function tryCatch<T>(promise: Promise<T>): Promise<Result<T>> {
  try {
    return { ok: true, value: await promise };
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err : new Error(String(err)) };
  }
}

const result = await tryCatch(fetch("/api/user").then((r) => r.json()));

if (result.ok) {
  console.log(result.value);
} else {
  console.error(result.error.message);
}
```


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.


```typescript
// Looks safe, but the caller picks T and nothing checks it
async function getJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  return res.json();
}

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.


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


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


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


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


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

// Clearer
function format(value: string | number): string {
  return String(value);
}
```


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.
