NoInfer utility trade-offs
Concept and syntax
NoInfer<T> blocks inference candidates from that position without changing the resulting assignability requirement. It is useful when one input should determine a type and another should be checked against it. Explicit type arguments can deliberately broaden the selected domain.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
function choose<T extends string>(allowed:readonly T[],fallback:NoInfer<T>):T{return allowed[0]??fallback;}console.log(choose(["tea","coffee"],"tea"),choose<string>(["tea"],"water"));Expected output:
tea teaCommon mistake
Intentionally invalid; compile separately and do not execute.
function choose<T extends string>(allowed:readonly T[],fallback:NoInfer<T>):T{return allowed[0]??fallback;}choose(["tea","coffee"],"water");Expected diagnostic: TS2345. water cannot widen T from the blocked position. Use a supported fallback or explicitly broaden the contract.
Independent comparison
Without NoInfer, water contributes an inference candidate even though the actual return is tea. Expected: 'tea\n'
function choose<T extends string>(a:readonly T[],b:T):T{return a[0]??b;} console.log(choose(["tea","coffee"],"water"));Practice and recap
Remove NoInfer and compare the rejected call.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
NoInfer utility trade-offs — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about NoInfer utility trade-offs is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function choose<T extends string>(allowed:readonly T[],fallback:NoInfer<T>):T{return allowed[0]??fallback;}console.log(choose(["tea","coffee"],"tea"),choose<string>(["tea"],"water"));Which diagnostic and explanation match the rejected example under the lesson settings?
function choose<T extends string>(allowed:readonly T[],fallback:NoInfer<T>):T{return allowed[0]??fallback;}choose(["tea","coffee"],"water");Which approach deliberately permits water in the NoInfer example?