← 中文资源

简体中文版本

交集类型组合契约

& 把多个独立接口叠成一个更严的类型:满足交集的值可安全传给任一组成契约;成员字段类型冲突时交集塌缩为 never,编译期即报错。

阅读英文原文

运行结果

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

id: rec-1 author: user-7
updatedAt via Timestamped: 2026-11-15T12:30:00.000Z
conflicting field collapses to never: true

实现说明

函数 stamp组织了整个示例的执行。

使用要点

  • 每一步打印都带着自己的标签:id:、updatedAt via Timestamped:、conflicting field collapses to never:。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件在加载时定义 stamp。

主要签名是 function stamp(t: Timestamped)

核心语句

const neverCheck: ExpectNever = true;
authorId: string;
createdAt: Date;

代码示例

// 三个独立契约,各自可单独实现与测试
interface Identifiable {
  id: string;
}

interface Timestamped {
  createdAt: Date;
  updatedAt: Date;
}

interface Authorable {
  authorId: string;
}

// 交集类型把契约叠成一个更严的类型:多一个成员都不可少
type AuditRecord = Identifiable & Timestamped & Authorable;

const record: AuditRecord = {
  id: "rec-1",
  createdAt: new Date("2026-11-15T10:00:00Z"),
  updatedAt: new Date("2026-11-15T12:30:00Z"),
  authorId: "user-7",
};

// 交集类型的值可安全传给任一组成契约的函数
function stamp(t: Timestamped): Date {
  return t.updatedAt;
}
console.log("id:", record.id, "author:", record.authorId);
console.log("updatedAt via Timestamped:", stamp(record).toISOString());

// 字段冲突时交集取两者之积:string & number 只剩 never
type Weird = { tag: string } & { tag: number };
type ExpectNever = [Weird["tag"]] extends [never] ? true : false;
const neverCheck: ExpectNever = true;
console.log("conflicting field collapses to never:", neverCheck);