【问题标题】:Record Type Reverser记录类型反转器
【发布时间】:2021-12-30 09:35:48
【问题描述】:

我想反转具有唯一常量属性值的记录的属性名称和类型。

const VALUE = {
    field1: "fieldA",
    field2: "fieldB"
} as const

type Reversed = Reverser<typeof VALUE>

//which should yield the following type
type Reversed = {
    fieldA: "field1";
    fieldB: "field2";
} 

我认为这是不可能的,因为属性值不一定是唯一的。但我还是问了 ;-)

【问题讨论】:

    标签: typescript mapped-types


    【解决方案1】:

    您可以使用带有as 子句的映射类型:

    type Reverser<T extends Record<PropertyKey, PropertyKey>> = {
      [P in keyof T as T[P]]: P
    }
    

    Playground Link

    as 子句将采用 P 键并将其映射到其他任何内容。在这种情况下,我们将其映射到键 P (T[P]) 处的属性类型。对于属性的值,我们只使用P 作为类型。

    【讨论】:

    • 酷。似乎extends 子句有所作为
    • @robkuz 是的。 as 让很多事情变得更容易。如果没有它,我们可能会想出一个解决方案。但这会很丑。
    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2020-07-03
    • 2021-11-12
    • 2022-08-10
    相关资源
    最近更新 更多