rid rid - 3 months ago 27
TypeScript Question

Generic type of object value parameter



function getValues<T, U extends { [key: string]: T }>(object: U): T[] {
// ...
}

const test = { a: 123, b: 234 };
const values = getValues(test);


In the above code, I expect
values
to be of type
number[]
, but the actual type is
{}[]
.

What am I doing wrong?

Answer

The type for this { a: 123, b: 234 } object is:

{ a: number; b: number; }

And not

{ [key: string]: number }

You can do:

const test = { "a": 123, "b": 234 } as { [key: string]: number };

To tell the compiler that it's indeed what you want.
But even then you still won't get the type you want for values:

const values = getValues(test); // type of values {}[]

You should do:

function getValues<T>(object: { [key: string]: T }): T[] {
    return null;
}

const test = { "a": 123, "b": 234 } as { [key: string]: number };
const values = getValues(test);

(code in playground)