Codectionary / Developer documentation / TypeScript

Choosing Inference Sources with NoInfer

NoInfer<T>, added in TypeScript 5.4, prevents a position from contributing candidates while inferring T. The position is still checked against the resulting type. This is useful when a list of allowed values should determine the type and a default value should only be checked against it.

Syntax

function choose<T extends string>(choices: T[], fallback: NoInfer<T>): T { return fallback; }

Examples

Choosing Inference Sources with NoInfer: working example

Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints small; the commented medium fallback is rejected.

function choose<T extends string>(choices: T[], fallback: NoInfer<T>): T {
  if (!choices.includes(fallback)) throw new Error("Invalid choice");
  return fallback;
}
console.log(choose(["small", "large"], "small"));
// choose(["small", "large"], "medium"); // Type error in TS 5.4+.
  1. Expected result: The program prints small; the commented medium fallback is rejected.
  2. T is inferred from choices, while NoInfer prevents the fallback from widening it.
  3. The runtime includes check still protects calls from untyped JavaScript.

Best practices

  • Use NoInfer only when the source of type inference must be controlled.
  • Document the TypeScript 5.4 minimum for libraries exposing this utility.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading