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
}