实现说明
顶层对象字面量把 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');