Let’s assume there is a object definition:
type Obj = {
i: number
b: boolean
s: string
}
I want to define a type which would allow me to pass property name and a callback which would expect single argument with exactly the same type as a property:
const a: FormatEntry = {
accessor: 'b',
formatter: (value: boolean) => value ? 'a' : 'b'
}
My best try to far
type FormatEntry<K extends keyof Obj> = {
accessor: K,
formatter: (value: Obj[K]) => string
}
But it gives me an error “Generic type ‘FormatEntry’ requires 1 type argument(s).(2314)” which I don’t understand – I would expect TS to infer the generic’s argument on its own
Sure, I can provide that argument:
const a: FormatEntry<'b'> = {
accessor: 'b',
formatter: (value: boolean) => value ? 'a' : 'b'
}
but it’s double work. What am I doing wrong?
2