Reputation: 3
Suppose I have this function declaration:
function foo<T extends {}>(bar: Array<{ key: keyof T, value: any, otherParam: string}>): T[]
And I have this interface:
interface C {
d: string
e: number
}
When I call foo like this:
foo<C>([{key: 'd', value: 'myValue', otherParam: 'other'}, {key: 'e', value: 100, otherParam: 'other'}])
I want to infer the type of the second parameter value
and get rid of that awful any
.
How can I do that?
Thanks!
Upvotes: 0
Views: 106
Reputation: 25790
Use mapped types to convert T
to your desired shape.
type Bar<T> = {
[P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];
Full solution:
type Bar<T> = {
[P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];
declare function foo<T extends object>(bar: Bar<T>[]): T[]
interface C {
d: string
e: number
}
foo<C>([{key: 'd', value: 'string', otherParam: 'other'}, {key: 'e', value: 100, otherParam: 'other'}])
Upvotes: 1