← 中文资源

简体中文版本

XOR 类型排除重叠字段

用 Exclude 映射出 never 可选键构造 XOR 助手:两个分支各自可选、同时填写则被编译期拒绝,@ts-expect-error 负向验证这一约束。

阅读英文原文

运行结果

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

[email protected] @ops-team
both rejected at compile time

实现说明

顶层对象字面量把 email 定成普通值——没有派生,背后也没有导入。

使用要点

  • 演示输出是带标签的(both rejected at compile time),每个操作都会留下自己的一行标注。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。

核心语句

type Without<T, U> = { [K in Exclude<keyof T, keyof U>]?: never };

代码示例

type Without<T, U> = { [K in Exclude<keyof T, keyof U>]?: never };

// XOR keeps A and B selectable but never together: never optionals
// poison overlapping keys so the two branches cannot both fill in
type XOR<A, B> = (Without<A, B> & B) | (Without<B, A> & A);

type Contact = XOR<{ email: string }, { handle: string }>;

const byEmail: Contact = { email: '[email protected]' };
const byHandle: Contact = { handle: '@ops-team' };
console.log(byEmail.email, byHandle.handle);

// @ts-expect-error - both fields together is the state XOR exists to prevent
const both: Contact = { email: '[email protected]', handle: '@ops' };
console.log('both rejected at compile time');