← 中文资源

简体中文版本

NoInfer 阻断参数类型推断

用 NoInfer 把类型参数的推断固定在单个参数上:越界实参不再悄悄撑宽 T,而是直接编译报错;对照版本演示撑宽后调用者意图被静默丢弃的过程。

阅读英文原文

实现说明

逻辑集中在函数 pickLoose、pickStrict里。

使用要点

  • 跑完文件,输出里会留下标记——strict:、loose widened:。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 文件在加载时定义 pickLoose、pickStrict。

核心语句

return options.includes(preferred) ? preferred : options[0] ?? preferred;
const modes = ['read', 'write'] as const;

代码示例

// 没有 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');