NoInfer
Concept and syntax
NoInfer<T> blocks that occurrence of T from contributing inference candidates while retaining compatibility checking against the inferred T. It is built in since TypeScript 5.4. Infer the permitted options from the first argument and check the default against them without letting the default widen the allowed set.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function choose<T extends string>(options:readonly T[],fallback:NoInfer<T>):T{return options[0] ?? fallback;}console.log(choose(["red","blue"],"blue"));Expected output:
redComparison without NoInfer
The compiler accepts this separate example because the fallback can contribute another candidate. It prints red. Acceptance of green here shows why the constraint on inference matters, even if the fallback is not used at runtime.
function choose<T extends string>(options:readonly T[],fallback:T):T{return options[0] ?? fallback;}choose(["red","blue"],"green");console.log(choose(["red","blue"],"green"));Common mistake
Intentionally invalid; compile separately and do not execute.
function choose<T extends string>(options:readonly T[],fallback:NoInfer<T>):T{return options[0] ?? fallback;}choose(["red","blue"],"green");Expected diagnostic: TS2345. green is not part of the inferred options. Choose a permitted default.
Practice and recap
Remove NoInfer and compare whether an extra default is accepted.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
NoInfer — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function choose<T extends string>(options:readonly T[],fallback:NoInfer<T>):T{return options[0] ?? fallback;}console.log(choose(["red","blue"],"blue"));Which diagnostic and explanation match the rejected example under the lesson settings?
function choose<T extends string>(options:readonly T[],fallback:NoInfer<T>):T{return options[0] ?? fallback;}choose(["red","blue"],"green");