Sorry if this question has been addressed before, but I'm having trouble finding the right search terms. Feel free to correct my question if necessary.
This is what I have:
type RowData = Record<string, unknown> & {id: string};
type Column<T extends RowData, K extends keyof T> = {
key: K;
action: (value: T[K], rowData: T) => void;
}
type RowsAndColumns<T extends RowData> = {
rows: Array<T>;
columns: Array<Column<T, keyof T>>;
}
I want TypeScript to automatically infer the types of the action
functions based on the structure of the rows and column keys:
For example:
function myFn<T extends RowData>(config: RowsAndColumns<T>) {
}
myFn({
rows: [
{id: "foo",
bar: "bar",
bing: "bing",
bong: {
a: 99,
b: "aaa"
}
}
],
columns: [
{
key: "bar",
action: (value, rowData) => {
console.log(value);
}
},
{
key: "bong",
action: (value, rowData) => {
console.log(value.a); //Property 'a' does not exist on type 'string | { a: number; b: string; }'.
}
}
]
});
The issue here is that TypeScript seems to be inferring the type of value (value: T[K]
) as 'the types accessible by all keys of T' rather than just the key provided in the column object.
Why is TypeScript behaving like this, and how can it be resolved?
A helpful response would involve defining specific terms and concepts.
It seems like modifying K extends keyof T
to allow for 'K being a single fixed key from T' could be a solution.