我有一堆对象,它们都有一个属性来区分它们。我将它们作为联合类型。现在我想创建从可区分属性到实际类型的映射。我可以自己制作它,但它是两面性的并且容易出错,所以我想知道是否有某种方法可以使用 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
),你可以使用以下类型:
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游乐场 https://www.typescriptlang.org/play/#src=type%20X%20%3D%20%7B%20type%3A%20%22x%22%2C%20x%3A%20number%20%7D%0D%0Atype%20Y%20%3D%20%7B%20type%3A%20%22y%22%2C%20y%3A%20number%20%7D%0D%0A%0D%0Atype%20Value%20%3D%20X%20%7C%20Y%0D%0Atype%20Type%20%3D%20Value%5B%22type%22%5D%0D%0A%0D%0A%2F%2F%20Is%20it%20possible%20to%20generate%20this%3F%0D%0Atype%20TypeToValue%20%3D%20%7B%0D%0A%20%20%20%20x%3A%20X%2C%0D%0A%20%20%20%20y%3A%20Y%2C%0D%0A%7D%0D%0A%0D%0A%2F%2F%20--%0D%0A%0D%0Atype%20TypeToValue2%3CT%20extends%20Type%3E%20%3D%20%7B%20%5BP%20in%20T%5D%3A%20number%20%7D%20%26%20%7B%20type%3A%20T%20%7D%0D%0A%0D%0Adeclare%20function%20getRecord%3CT%20extends%20Type%3E(type%3A%20T%2C%20id%3A%20string)%3A%20TypeToValue2%3CT%3E%0D%0A%0D%0Aconst%20%7B%20type%2C%20x%20%7D%20%3D%20getRecord('x'%2C%20'aa')%3B
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)