【问题标题】:How do I convert an integer from a Typescript enum to its key value as a type of the union of the keys?如何将 Typescript 枚举中的整数转换为其键值作为键的联合类型?
【发布时间】:2017-08-21 23:40:08
【问题描述】:

我在 Typescript 中有两个接口,一个使用枚举的整数值,一个使用枚举的键:

enum foo {
    bar = 0,
    baz,
}

interface asNumbers {
    qux: foo
}

interface asStrings {
    quux: keyof typeof foo
}

我想获取一个实现asNumbers 的对象并将其转换为一个实现asStrings 的对象。我有以下代码:

const numberObject: asNumbers = {
    qux: foo.bar
}

const stringyObject: asStrings = {
    quux: foo[numberObject.qux] 
}

虽然我在 stringyObject 分配中收到以下错误。

Type '{ quux: string; }' is not assignable to type 'asStrings'.
Types of property 'quux' are incompatible.
Type 'string' is not assignable to type '"bar" | "baz"'.

我不清楚如何获取该整数值并以类型安全的方式将其转换为它的键(不诉诸更通用的string 类型)。可在打字稿操场上重现:Typescript playground link

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以定义一个提供某种类型安全性同时满足您的用例的函数:

    const stringyObject: asStrings = {
        quux: getFooProp[numberObject.qux] 
    }
    
    function getFooProp(i: foo): (keyof typeof foo) { 
        return foo[i] as (keyof typeof foo);
    }
    

    如果你想更通用,那么你可以定义一个这样的函数:

    interface NumericEnum {
        [id: number]: string
    }
    
    function getEnumProp<T extends NumericEnum, K extends keyof T>(
        e: T,
        i: T[K]): (keyof T) { 
    
        return e[i] as (keyof T);
    }
    

    编译器在这两种情况下都对我们有帮助,并且当我们传入一个不是foo 类型的枚举值时会报错。

    // Works
    getEnumProp(foo, foo.bar);
    
    // Argument of type 'foo2.bar' 
    // is not assignable to parameter of type 'foo'.
    getEnumProp(foo, foo2.bar); 
    

    Here is a Fiddle for you 证明了两者。

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 1970-01-01
      • 2018-01-09
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2015-01-25
      相关资源
      最近更新 更多