TypeScript: Infer enum value type from enum type

前端 未结 1 1235
太阳男子
太阳男子 2021-01-12 05:45

I wrote a function returning all values of a given enum as array. The implementation works, but I have a problem with the type of the return value.

enum Foo          


        
相关标签:
1条回答
  • 2021-01-12 06:02

    You need to change the definition a bit to infer the type of the enum member, right now T will be the enum object itself (aka typeof T)

    enum Foo {
        FOO_1 = "FOO_1",
        FOO_2 = "FOO_2",
    }
    
    function getEnumValues<TEnum, TKeys extends string>(e: { [key in TKeys]: TEnum }): TEnum[] {
        let keys = Object.keys(e) as Array<TKeys>;
        keys = keys.filter(key => e[key] !== undefined);
        return keys.map(key => e[key]);
    }
    
    const fooValues: Foo[] = getEnumValues(Foo);
    

    Note that while this works for enums, it will work for any object it is not restricted to enums

    0 讨论(0)
提交回复
热议问题