Search code examples
angulartypescriptenumeration

Getting an Array of all items from an Enum in Typescript


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)


Solution

  • 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);