← 中文资源

简体中文版本

在泛型配置入参上拒绝多余属性键

把已赋值的变量传给泛型函数时默认会跳过多余属性检查;用 Record<Exclude<keyof Input, keyof Shape>, never> 封死未知键,让拼写错误在编译期暴露。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

applied: 3 250
exact keys: baseDelayMs,maxAttempts

实现说明

逻辑集中在函数 applyPolicy里。 返回值是携带 maxAttempts 的对象。

使用要点

  • 不需要依赖清单;标准库就是全部。
  • 直接运行文件,输出会带上标签,比如 applied:、exact keys:——输出的每一行都能指回产生它的那次调用。

常见问题

applyPolicy 会修改传入的参数吗?

不会修改。入参只读,返回值是全新构造的。

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 applyPolicy。

核心语句

return { maxAttempts: policy.maxAttempts, baseDelayMs: policy.baseDelayMs };
Record<Exclude<keyof Input, keyof Shape>, never>;
const keys = Object.keys(applied).sort();

代码示例

interface RetryPolicy {
  maxAttempts: number;
  baseDelayMs: number;
}

// Excess keys map to `never`, so even aliased variables fail when they carry extra fields
type Exact<Shape, Input extends Shape> = Input &
  Record<Exclude<keyof Input, keyof Shape>, never>;

function applyPolicy<const T extends RetryPolicy>(policy: Exact<RetryPolicy, T>): RetryPolicy {
  return { maxAttempts: policy.maxAttempts, baseDelayMs: policy.baseDelayMs };
}

const cleanVar = { maxAttempts: 3, baseDelayMs: 250 };
const applied = applyPolicy(cleanVar);
console.log('applied:', applied.maxAttempts, applied.baseDelayMs);

// With an extra field on an aliased variable, `Exact` flags `retires: never` at compile time:
// const typoVar = { maxAttempts: 3, baseDelayMs: 250, retires: 5 };
// applyPolicy(typoVar);

const keys = Object.keys(applied).sort();
console.log('exact keys:', keys.join(','));