← 中文资源

简体中文版本

Simplify 展平交叉类型

用一行映射类型把 Defaults 与 Overrides 的交叉展平成单一对象形态:悬停提示与 ExpectEqual 比较看到的都是干净结构,不再是两个成员的并排罗列。

阅读英文原文

运行结果

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

3 1500 billing
keys: label,retries,timeoutMs

实现说明

一个对象字面量承载 retries、label——每个值都就地写死。

使用要点

  • 每一步打印都带着自己的标签:keys:。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。

核心语句

(<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : never;
type Simplify<T> = { [K in keyof T]: T[K] } & {};

代码示例

// A homomorphic mapped type copies every key once, collapsing an
// intersection of object types into one flat shape for hover and compare.
type Simplify<T> = { [K in keyof T]: T[K] } & {};

interface BaseConfig {
  retries: number;
  timeoutMs: number;
}

type Overrides = { timeoutMs?: number; label?: string };

// Raw intersections keep both members listed; Simplify merges them
type ResolvedRaw = BaseConfig & Required<Overrides>;
type Resolved = Simplify<ResolvedRaw>;

type ExpectEqual<T, U> =
  (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : never;

type Checks = [
  ExpectEqual<Resolved, { retries: number; timeoutMs: number; label: string }>,
];
type _Checks = Checks;

const resolved: Resolved = { retries: 3, timeoutMs: 1_500, label: 'billing' };
console.log(resolved.retries, resolved.timeoutMs, resolved.label);
console.log('keys:', Object.keys(resolved).sort().join(','));