Typescript: How to convert enum type to Array<Object>

Created on 13 Dec 2016  ·  3Comments  ·  Source: microsoft/TypeScript

I want convert enum type to Array.

example :

enum A {
dog = 1,
cat = 2,
ant = 3
}

convert to: [{id: 1, name: 'dog'}, {id: 2, name: 'cat'}, {id: 3, name: 'ant'}]

thank you.

Question

Most helpful comment

@narutomxc

This is an issue tracker, not a standard help forum. But anyways, here's how you'd do it:

// This requires TypeScript 2.1.
// If you need older versions, use `string` instead of `keyof E`.
interface EnumItem<E> { id: E; name: keyof E; }

function enumToArray<E>(Enum: {[keyof E]: E}): EnumItem<E>[] {
    return Object.keys(Enum).map(key => ({id: Enum[key], name: key} as EnumItem<E>))
}

All 3 comments

@narutomxc

This is an issue tracker, not a standard help forum. But anyways, here's how you'd do it:

// This requires TypeScript 2.1.
// If you need older versions, use `string` instead of `keyof E`.
interface EnumItem<E> { id: E; name: keyof E; }

function enumToArray<E>(Enum: {[keyof E]: E}): EnumItem<E>[] {
    return Object.keys(Enum).map(key => ({id: Enum[key], name: key} as EnumItem<E>))
}

OK, thx

I found {[keyof E]: E} cannot be recognise in Webstorm. so replace it with any...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

manekinekko picture manekinekko  ·  3Comments

seanzer picture seanzer  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments

wmaurer picture wmaurer  ·  3Comments

uber5001 picture uber5001  ·  3Comments