Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 96 ยท Generics

Generic Constraints and Defaults

Learn to limit TypeScript type parameters with extends and keyof, give them defaults, keep literal types with const type parameters and control inference with NoInfer.

A plain type parameter like T accepts anything, so inside the function you can do almost nothing with it: you can't read .length, call a method or look up a property, because T might be a number, null or a function. Constraints fix that. Writing T extends Something says "T can be any type, as long as it's assignable to Something", and in return you may use everything Something guarantees.

This lesson covers constraints with extends and keyof, the subtle "could be instantiated with a different subtype" error, constraints that refer to other type parameters, default type arguments, const type parameters (TypeScript 5.0) for preserving literal types, and the NoInfer utility (TypeScript 5.4) for steering inference. You should be comfortable with Generics first.

extends: requiring a minimum shape

Here's a function that returns the longer of two values. Strings, arrays and anything else with a numeric length should work:

TypeScript A constraint unlocks members of T

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.

Inside longest, a.length is allowed because every possible T has a length. And the result is still the specific type: custom.label works because T was inferred as { length: number; label: string }, not as HasLength. That's the whole point of a constraint over a plain parameter type: function longest(a: HasLength, b: HasLength): HasLength would also compile, but it would forget label.

Callers that don't satisfy the constraint get a clear error:

TypeScript Breaking the constraint (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(5,21): error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

"T could be instantiated with a different subtype"

A constraint is a lower bound on what T has, not a description of what T is. This is the source of one of TypeScript's most confusing messages. Look at a function that tries to return a fresh object:

TypeScript Returning a new object as T (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(6,3): error TS2322: Type '{ length: number; }' is not assignable to type 'T'.
  '{ length: number; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'HasLength'.

The signature promises: "give me a T, get back that same T." If a caller passes a string, T is string, and { length: 0 } is certainly not a string. The compiler is right. The fix depends on what you meant: return HasLength if any object with a length will do, or construct the result from the input, so that it really is a T.

keyof constraints: safe property access

The most common constraint relates one type parameter to another. K extends keyof T means "K must be one of T's property names". Combined with the indexed access type T[K] ("the type of property K in T"), you can write fully typed property helpers:

TypeScript getProperty, pluck and setProperty

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 return types follow the key you pass: 'year' gives number, 'tags' gives string[]. Without @ts-expect-error, the two bad calls would fail with Argument of type '"author"' is not assignable to parameter of type 'keyof Book'. and Argument of type 'string' is not assignable to parameter of type 'number'. for the string '1966'. keyof, typeof and Indexed Access Types explains keyof and T[K] in depth.

Constraints that use other type parameters

A constraint may mention any type parameter declared in the same list. That lets you express rules such as "the second object may only contain properties of the first", or "the key must point at a string property":

TypeScript Constraints that refer to each other

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.

StringKeys<T> is a small preview of mapped and conditional types: it produces 'name' | 'country' for City. You don't need to write types like this every day, but it shows how far constraints can go.

Default type parameters

Type parameters can have defaults, written with =, just like function parameters. A default is used when a type argument is neither written nor inferable. Defaults are most useful on generic types, where users often write the type without arguments, but they work on functions too:

TypeScript Defaults for 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.

Inference always wins over the default: createList(1, 2) infers 1 | 2. Only createList(), with nothing to infer from, falls back to string. Two rules to remember: a default must satisfy its own constraint, and parameters with defaults must come after required ones, or you get error TS2706: Required type parameters may not follow optional type parameters.

const type parameters (TypeScript 5.0)

By default, inference widens literals inside objects and arrays: an argument ['/', '/about'] becomes string[]. Callers could write as const at every call site, but that's easy to forget. A const type parameter asks TypeScript to infer as if the caller had written as const:

TypeScript const type parameters keep literal 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.

The const modifier only affects literals written directly in the call. If you pass a variable that's already typed string[], there's nothing left to preserve. Pairing const with a readonly array constraint is the idiomatic form, because it also accepts arrays that callers already declared read-only.

NoInfer (TypeScript 5.4)

When a type parameter appears in several parameters, TypeScript gathers inference candidates from all of them. Sometimes one parameter should only be checked against T, never used to infer it. The built-in NoInfer<T> marks such a spot:

TypeScript NoInfer stops a parameter from widening T (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(8,49): error TS2345: Argument of type '"stopped"' is not assignable to parameter of type '"idle" | "running"'.

S is inferred only from states, giving 'idle' | 'running', and then 'stopped' is checked against it and rejected. Without NoInfer, TypeScript would happily infer S as 'idle' | 'running' | 'stopped' from both arguments, and the typo would compile. NoInfer is erased like every type; it changes nothing at runtime.

TypeScript Default values that must match the options

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 two as casts in select are deliberate and safe: includes just proved that input is one of the options, but TypeScript can't connect that runtime check to T. Keeping the casts inside one small, tested function is a reasonable trade-off.

Choosing the right tool

You want to... Use
Use members of T inside the function T extends SomeShape
Accept only property names of an object K extends keyof T, with T[K] for the value
Let callers omit a type argument A default: T = string
Keep literal types of arguments const T extends readonly ...
Check a parameter against T without inferring from it NoInfer<T>
Return something not built from the input A concrete return type, not T

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Does longest(10, 20) compile, where function longest<T extends { length: number }>(a: T, b: T): T?

    Numbers have no length property, so the argument fails the constraint with TS2345.
  2. 2. Why does function f<T extends { id: number }>(x: T): T { return { id: 1 }; } fail?

    The signature promises to return the same T the caller passed. A new object only matches the constraint, not every possible T.
  3. 3. What is the type of getProperty(book, 'year') with getProperty<T, K extends keyof T>(obj: T, key: K): T[K] and book: { title: string; year: number }?

    K is inferred as the literal 'year', and T['year'] is number.
  4. 4. With function f<const T extends readonly string[]>(x: T): T, what is the type of f(['a', 'b'])?

    The const modifier makes inference behave as if the caller had written as const, so the literal tuple is kept.
  5. 5. What does wrapping a parameter type in NoInfer do?

    NoInfer removes that position from inference. The argument is still checked against the type inferred elsewhere, which catches typos such as an initial state that is not in the list.

Summary

  • T extends Shape limits a type parameter to types assignable to Shape and lets you use Shape's members inside the function, while callers still get their specific type back.
  • A constraint is a minimum, not an exact type: returning a new object as T fails with "could be instantiated with a different subtype".
  • K extends keyof T with T[K] gives type-safe property access; constraints may refer to other type parameters.
  • Defaults (T = string) apply only when nothing can be inferred; they must satisfy the constraint and come after required parameters (TS2706).
  • const type parameters (5.0) keep literal types of arguments, like an automatic as const.
  • NoInfer<T> (5.4) makes a parameter check against T without influencing inference.

Next: Generic Interfaces, Classes and Types