实现说明
逻辑集中在函数 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(','));