Reputation: 3593
Following enum
export enum Types {
Type1 = 1,
Type2 = 2,
...
}
is converted into array with following function
export function EnumKeys<T>(obj: object): string[] {
return Object.keys(obj)
.filter(value => isNaN(Number(value)) === false)
.map(key => obj[key]);
}
EnumKeys returns string[], but I need it to return [keyof typeof T]
Upvotes: 2
Views: 448
Reputation: 249606
Object.keys
returns string[]
by design (see canonical question here). You will need to use a type to transform Object.keys(obj)
into Array<keyof T>
(I assume for the type of obj
you wanted to use the T
type parameter).
enum Types {
Type1 = 1,
Type2 = 2,
}
function EnumKeys<T>(obj: T) {
return (Object.keys(obj) as Array<keyof T>)
.filter(value => isNaN(Number(value)) !== false); // just directly take the non number keys.
}
let o = EnumKeys(Types)
console.log(o)
Upvotes: 3