Intersection Types Compose Contracts
The & operator stacks independent interfaces into one stricter type, and a conflicting field between members collapses to never at compile time.
Code
// 三个独立契约,各自可单独实现与测试
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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
id: rec-1 author: user-7
updatedAt via Timestamped: 2026-11-15T12:30:00.000Z
conflicting field collapses to never: trueHow the snippet works
Intersection Types Compose Contracts keeps everything in the function stamp.
Using it
The primary signature is function stamp(t: Timestamped)
Look for the id:, updatedAt via Timestamped:, conflicting field collapses to never: prefixes when the file runs; they tie each line to its step.
Key statements
const neverCheck: ExpectNever = true;
authorId: string;
createdAt: Date;
Interactive Tools for This Topic
Docker Run to Compose ConverterTransform docker run CLI commands with ports, environment variables, volumes, networks, and resource limits into clean compose.yaml service definitions.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `stamp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.