实现说明
迭代发生在 for (const t of tagged) console.log(${t.errorKind}: ${t.error.kind}); 内部——循环之外的语句只执行一遍。
顶层对象字面量把 kind、status 定成普通值——没有派生,背后也没有导入。
使用要点
- 跑完文件,输出里会留下标记——
whole wrapper holds union:、empty union stays never:。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。
核心语句
type Tagged<T> = T extends { kind: infer K } ? { errorKind: K; error: T } : never;
代码示例
// A naked type parameter inside a conditional type evaluates per union member -
// that is distribution; the results reassemble into a union
type FieldError = { kind: 'missing'; field: string };
type StatusError = { kind: 'http'; status: number };
type RequestError = FieldError | StatusError;
type Tagged<T> = T extends { kind: infer K } ? { errorKind: K; error: T } : never;
// Each member gets its own errorKind literal (distribution active)
type TaggedErrors = Tagged<RequestError>;
// Proof distribution is on: errorKind and error must come from the same member - mixing is a compile error
// const mismatch: TaggedErrors = { errorKind: 'missing', error: { kind: 'http', status: 500 } };
const tagged: TaggedErrors[] = [
{ errorKind: 'missing', error: { kind: 'missing', field: 'email' } },
{ errorKind: 'http', error: { kind: 'http', status: 503 } },
];
for (const t of tagged) console.log(`${t.errorKind}: ${t.error.kind}`);
// Wrapping the type parameter in a tuple turns distribution off: the union evaluates once as a whole
type Whole<T> = [T] extends [unknown] ? { all: T } : never;
type Wrapped = Whole<RequestError>;
// Proof it is off: all accepts the entire union (a compile error while distribution is on)
const either: RequestError = { kind: 'http', status: 418 };
const single: Wrapped = { all: either };
console.log('whole wrapper holds union:', single.all.kind);
// never distributes to never: an empty union has no members to enumerate
type Empty = Tagged<never>;
const emptyIsNever: Empty extends never ? true : false = true;
console.log('empty union stays never:', emptyIsNever);