4

I'm trying to get all items of a TypeScript Enumeration. For this I use the following, generic function:

static getAllValues<T>(enumeration: T): Array<T>{
    let enumKeys: Array<T> = Object.keys(enumeration).map(k => enumeration[k]);

    let items: Array<T> = new Array<T>();
    for(let elem of enumKeys){
        if (typeof(elem) === "number"){
            items.push(elem)
        }
    }

    return items;
}

By calling this function with an Enum of the Type ExampleEnum like

export enum ExampleEnum {
 FOO,
 BAR,
 FOOBAR
}

I expected a return value from the type Array<ExampleEnum> but the response is from the type Array<typeof ExampleEnum>.

Does anyone know how to fix it, to get a return from the type Array<ExampleEnum>?

(I'm using TypeScript 3.2.1)

2 Answers 2

3

You are passing in the container object for the enum so T will be the container object. The container object is not the same type as the enume, it is an object that contains values of the enum, so its values will be of the enum type which we can get at using T[keyof T]

function getAllValues<T>(enumeration: T): Array<T[keyof T]> {
    let enumKeys = Object.keys(enumeration).map(k => enumeration[k]);

    let items = new Array<T[keyof T]>();
    for (let elem of enumKeys) {
        if (typeof (elem) === "number") {
            items.push(elem as any)
        }
    }

    return items;
}

export enum ExampleEnum {
    FOO,
    BAR,
    FOOBAR
}

getAllValues(ExampleEnum);
Sign up to request clarification or add additional context in comments.

Comments

3

What do you think of this version of the function, shorter and still handling string enum too?

function enumValues<T extends object>(enumeration: T): Array<T[keyof T]> {
    return Object
        .keys(enumeration)
        .filter(k => isNaN(Number(k)))
        .map(k => enumeration[k]);
}

enum ExampleEnum {
    FOO = 10,
    BAR = 20,
    BAZ = 30
}

console.log(enumValues(ExampleEnum)); // [10, 20, 30]

enum ExampleStringEnum {
    FOO = 'F',
    BAR = 'B',
    BAZ = 'Z'
}

console.log(enumValues(ExampleStringEnum)); // ['F', 'B', 'Z']

1 Comment

Wow, I did not think about that. Although I do not need the string values but through the early filtering, the computing effort will probably be significantly reduced. Thanks!

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.