Currently I have the following setup.
When I pass foo
as Column.key, I want the type of the argument value
for Column.formatter to be string
. For bar
it should be number
.
As is; Typescript expects the type to be all possible types on T
. So string
or number
.
Is it possible to set the type based on the given key?
interface ColumnData {
foo: string;
bar: number;
};
type ColumnDataFormatter<T> = (value: T[keyof T]) => string;
class Column<T> {
constructor(
public key: keyof T,
public formatter: ColumnDataFormatter<T>
) {}
}
new Column<ColumnData>('foo', (value: string) => value);
new Column<ColumnData>('bar', (value: number) => value.toString());
-------------------------------------------------------------------
ERROR: TS2345
Types of parameters 'value' and 'value' are incompatible.
Type 'string | number' is not assignable to type 'string'.