简体   繁体   English

是否可以使用 TypeScript 中的映射类型创建可区分联合?

[英]Is it possible to create a discriminated union using mapped types in TypeScript?

Suppose I have the following interface X :假设我有以下接口X

type X = {
  red: number, 
  blue: string
}

Is it possible to construct a union type Y using mapped types?是否可以使用映射类型构造联合类型Y If not, can it be constructed with other kind of type-level mechanisms?如果不是,是否可以使用其他类型的类型级机制来构建它?

type Y = {
  kind: "red"
  payload: number
} | {
 kind: "blue"
 payload: string
}

Yes, you can make use of the fact that T[keyof T] is a union of the values of T , whatever T is.是的,您可以利用T[keyof T]T的值的联合这一事实,无论T是什么。 You can use a mapped type to construct a type whose values are the branches of the union you want:您可以使用映射类型来构造一个类型,其值是您想要的联合的分支:

type Y = { [K in keyof X]: {kind: K, payload: X[K]} }[keyof X]

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM