【问题标题】:Mapping from discriminated union property to object type从可区分的联合属性映射到对象类型
【发布时间】:2017-12-22 06:27:46
【问题描述】:

我有一堆对象,它们都具有区分它们的属性。我将它们作为联合类型。现在我想创建一个从可区分属性到实际类型的映射。我可以自己制作,但它具有欺骗性且容易出错,所以我想知道是否有某种方法可以使用 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
}

【问题讨论】:

标签: typescript typescript-typings


【解决方案1】:

如果签名始终与您帖子中的相同,而 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 Playground

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 2021-12-11
    • 2019-04-06
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2022-01-03
    • 2020-01-25
    相关资源
    最近更新 更多