11

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 {
    FOO_1 = "FOO_1",
    FOO_2 = "FOO_2",
}

function getEnumValues<T>(e:T): T[] {
    let keys: string[] = Object.keys(e);
    keys = keys.filter(key => e[key] !== undefined);
    return keys.map(key => e[key]);
}

const fooValues:Foo[] = getEnumValues(Foo);

I get this error:

Error:(46, 7) TS2322: Type '(typeof Foo)[]' is not assignable to type 'Foo[]'. Type 'typeof Foo' is not assignable to type 'Foo'.

How can I change the signature of getEnumValues() in order to return the type Foo[] here?

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

4 Comments

Apart from being way less specific, you could just change e:any, and it would work too.
@Marco well .. you can type anything as any and it will work. The art of using Typescript is never using any :P. Also if you use e:any you have to also give a type argument to have the corect enum type (ie getEnumValues<Foo>(Foo), like this it is inferred.
It does work without specifying the concrete type - at least in this case.
Agreed. I'm just being lazy here.
0

Personaly I do this:

enum Foo {
    FOO_1 = "FOO_1",
    FOO_2 = "FOO_2",
}

const fooValues:Foo[] = Object.values(Foo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.