从可区分联合属性到对象类型的映射 [英] Mapping from discriminated union property to object type
问题描述
我有一堆对象,它们都有一个属性来区分它们.我将它们作为联合类型.现在我想创建一个从被区分属性到实际类型的映射.我可以自己制作,但它具有两面性且容易出错,所以我想知道是否有某种方法可以使用 TypeScript 以编程方式生成它.:)
I have a bunch of objects that all have a property to discriminate them. And I have them as a union type. Now I want to create a mapping from the discriminated property to the actual type. I can make it myself, but its duplicitous and error prone so I was wondering if there was some way of generating this programmatically with TypeScript. :)
type X = { type: "x", x: number }
type Y = { type: "y", y: number }
type Value = X | Y
type Type = Value["type"]
// Is it possible to generate this?
type TypeToValue = {
x: X,
y: Y,
}
// Its useful for stuff like this
function getRecord<T extends Type>(type: T, id: string): TypeToValue[T] {
return null as any
}
推荐答案
如果签名始终与您的帖子相同,而 type
的值必须匹配关联属性(例如 x
| y
),您可以使用以下类型:
If the signature is always the same as in your post, whereas the value of type
must match the associating property (e.g. x
| y
), you can get away with the following type:
type TypeToValue<T extends Type> = { [P in T]: number } & { type: T }
可以如下使用:
declare function getRecord<T extends Type>(type: T, id: string): TypeToValue<T>
const { type, x } = getRecord('x', 'aa');
无法从与 type
参数匹配的联合类型中获取相应的类型.TS Playground
There is no way to get the corresponding type from the union type that matches the type
argument. TS Playground
这篇关于从可区分联合属性到对象类型的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!