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+.- Expected result: The program prints small; the commented medium fallback is rejected.
- T is inferred from choices, while NoInfer prevents the fallback from widening it.
- 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