TypeScript Reference ยท Utility Types
TypeScript NoInfer<T> utility type
Reference for NoInfer<T> in TypeScript 5.4: stop a parameter from contributing to generic inference so another argument decides the type parameter.
NoInfer<T> tells the compiler: "do not use this position to work out what T is." The type of the argument is still checked against T, but it does not add a candidate for T. Other positions decide it.
The problem it solves is a default or fallback parameter that quietly widens a type parameter. If colors: C[] and fallback: C both infer C, passing a fallback that is not in the list widens C to include it instead of reporting an error. Marking the fallback NoInfer<C> makes the list the single source of truth. It was added in TypeScript 5.4 as an intrinsic type.
declare function pick<C extends string>(choices: C[], fallback: NoInfer<C>): C;
Try it
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.
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.
Syntax
type NoInfer<T> = intrinsic;
| Name | Description |
|---|---|
T |
The type to protect. Usually a type parameter of the enclosing function, class or alias. |
Returns: a type that is equivalent to T for assignability but is opaque to inference, so it is not a candidate source when solving type parameters.
Edge cases:
NoInfer<T>whereTis not a type parameter (NoInfer<string>) is juststring.- If every position that mentions
Tis wrapped inNoInfer, inference has no candidates andTfalls back to its constraint (orunknown). - The blocking only affects inference. After
Tis fixed from another argument, the value is checked against it normally.
Usage notes
- Put it on the parameters that should consume the type parameter, not on the one that should define it.
- Typical uses: default values, "initial state" arguments, a
currentvalue that must match a list of options, and callbacks whose return type should follow another argument. - An older trick was
T & {}or[T][T extends any ? 0 : never]. Those are fragile; useNoInferon TypeScript 5.4 and later. - It has no runtime effect and disappears after compilation.
- It does not stop
consttype parameters or literal widening from working; it only removes one inference site. See const type parameters. - For control over which side is "inferred first", see how type argument inference collects candidates.