You are likely confusing the named type myExample
with the named value myExample
. They are not the same, despite the same name. The type myExample
is the type of the enum values which are numbers. The value myExample
has type typeof myExample
, a map from keys value1
and value2
to those myExample
enum values. That is, typeof myExample
is something like {example1: myExample.example1, example2: myExample.example2}
.
(For more of my ranting about the difference between named values and named types in TypeScript, see this answer)
Therefore when you pass in the value myExample
to getArrayWithNumberBaseEnumItems()
, you are passing in typeof myExample
and want myExample[]
to come out. The way to get from the former to the latter is to do a lookup from T
(corresponding to typeof myExample
) to T[keyof T]
(meaning "the values of the properties of T
").
Thus you should amend your types to the following:
function getArrayWithNumberBaseEnumItems<T>(numberEnum: T): T[keyof T][] {
let arrayWithEnumItems: T[keyof T][] = [];
for (let item in numberEnum) {
if (isNaN(Number(item))) {
arrayWithEnumItems.push(numberEnum[item]); // no type assertion here
console.log(numberEnum[item]);
}
}
return arrayWithEnumItems;
}
Note how I've removed your type assertion of numberEnum[item]
to any
. The error you were suppressing:
// Argument of type 'T[Extract<keyof T, string>]'
// is not assignable to parameter of type 'T'.
(that's the error TS3.1 gives. TS2.6 probably gives a different-looking but similar error)
was trying to tell you that you were trying to push a property value onto an array of key-value maps, which was an error. Sometimes you need to assert to get things done, but this is not one of those times.
Okay, hope that helps. Good luck!