I am creating a complex table configuration type, where I would like to infer the type of a value based on an accessor key.
The column configuration type looks like
type ColumnConfig<Row,Acc extends keyof Row = keyof row> = {
accessor: Acc;
render: React.FC<{value: Reducer<A, Row>}>;
}
The above works absolutely fine when both args are passed:
const foo: ColumnConfig<{foo: 'bar'}, 'bar'> = {
accessor: 'bar',
render: ({value}) => <></> // Value type hint is 'bar'
}
However, I don’t always want to pass in the generic arg, as I would like to infer it.
const foo: ColumnConfig<{foo: 'bar'}> = {
accessor: 'bar',
render: ({value}) => <></> // Value type hint is keyof {foo: 'bar'}
}
It feels like typescript is refusing to infer the type whenever I pass any of the generic args. Is there a good way to get around this?
I have tried moving things around but I can’t get away without passing the Row type here, else I lose type hinting in the accessor field.
2
Answers
Perhaps, a mapped type should be fine for your case: TS Playground
It will let TypeScript infer the type of value directly from accessor
This is what you need, I guess