[英]Extend Discriminated Unions
is it possible to do transform this DU using mappend/conditional types是否可以使用 mappend/conditional 类型来转换这个 DU
type MyDU =
| {kind: 'foo'}
| {kind: 'bar'}
type Transformed = DUTransformer<MyDU>
such that we get the folllowing result这样我们就得到了以下结果
type Transformed =
| {kind: 'foo', foo: boolean}
| {kind: 'bar', bar: boolean}
Yes, because TypeScript will distribute mapped types over a union :是的,因为 TypeScript 会通过 union 分配映射类型:
type MyDU =
| {kind: 'foo'}
| {kind: 'bar'}
type Kinded<T extends string> = { kind: T }
type DUTransformer<T> = T extends Kinded<infer K> ? T & {[K1 in K]: boolean} : never
type Transformed = DUTransformer<MyDU>
The type of Transformed
is: Transformed
的类型是:
type Transformed = ({
kind: 'foo';
} & {
foo: boolean;
}) | ({
kind: 'bar';
} & {
bar: boolean;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.