NoInfer Blocks Parameter Type Inference
NoInfer pins type inference to one argument, so out-of-scope callback values fail compilation instead of silently widening the type parameter.
Code
// 没有 NoInfer:preferred 参与 T 的推断,越界值会把 T 撑宽
function pickLoose<T extends string>(options: readonly T[], preferred: T): T {
return options.includes(preferred) ? preferred : options[0] ?? preferred;
}
// NoInfer:T 只由 options 决定,preferred 必须已是同一窄类型
function pickStrict<T extends string>(options: readonly T[], preferred: NoInfer<T>): T {
return options.includes(preferred) ? preferred : options[0] ?? preferred;
}
const modes = ['read', 'write'] as const;
console.log('strict:', pickStrict(modes, 'write'));
console.log('loose widened:', pickLoose(modes, 'exec'));
// @ts-expect-error: "exec" is not one of the inferred options
pickStrict(modes, 'exec');Inside the snippet
The working surface is the functions pickLoose and pickStrict — everything else is wiring.
Putting it to use
The demo output is labeled (strict:, loose widened:), so every printed line maps back to a specific operation.
Core lines
return options.includes(preferred) ? preferred : options[0] ?? preferred;
const modes = ['read', 'write'] as const;
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `pickLoose`, `pickStrict` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.