Lets say I have an interface that accepts a generic:
interface ObjectKey<T extends {}>{
key: keyof T
doSomethingWithKey: (value: any) => void
}
Using it like this:
interface User {
name: string,
age: number,
archived: boolean
}
const nameKey: ObjectKey<User> = {
key: 'name',
doSomethingWithKey: (value) => console.log(value) // I want to infer value type here
}
As mentioned above i want to infer the 'value' argument type. Something like this:
interface ObjectKey<T extends {}>{
key: keyof T
doSomethingWithKey: (value: T[key]) => void
}
How can I achieve that?
I tried something like:
interface ObjectKey<T extends {}>{
key: keyof T
doSomethingWithKey: (value: { [Property in keyof T]: T[Property] }[keyof T]) => void
}
But it returns all available types of T. For example if we use User interface, 'value' argument would be 'string | number | boolean'
CodePudding user response:
We can make ObjectKey
a union type of all possible combinations by mapping over the object keys
type ObjectKey<T extends {}> = {
[K in keyof T]: {
key: K,
doSomethingWithKey: (value: T[K]) => void
}
}[keyof T]
interface User {
name: string,
age: number,
archived: boolean
}
const nameKey: ObjectKey<User> = {
key: 'age',
doSomethingWithKey: (value) => console.log(value)
}