Given I have a type like:
type Foo = {
foo: number;
bar: string;
baz: boolean;
}
I want to have a type Buzz which can detect the value type against a key, i.e
const abc: Buzz<Foo> = {
key: 'foo',
formatter: (detectMe) => {} //I want TS to infer this to be 'number'
};
Given the key 'foo' the argument in formatter should be inferred to be number. I tried this:
interface ColumnDescription<T> {
label: string;
key: keyof T;
formatter?: (datum: T[keyof T]) => void;
}
However this results in the argument being inferred to be number | string | boolean.
Tried this as well:
interface ColumnDescription<T, K extends keyof T> {
label: string;
key: K;
formatter?: (datum: T[K]) => void;
}
This sort of works but I always need the specify the key in the second type argument, instead of it happening automatically. i.e:
const abc: Buzz<Foo, 'foo'> = { //I don't want to specify the key
key: 'foo',
formatter: (detectMe) => {} //This is inferred correctly
};
type Buzz<T> = {[K in keyof T]-?: {key: K; formatter: (d: T[K])=>void}}[keyof T]