I am seeking a method to specify the type of a property based on the generic type of another property within the same context.
For instance, consider the following:
type Person = {
id: number;
name: string;
}
type Select<Value=unknown> = (props:Props<Value>) => any;
const PersonSelect:Select<Person> = (props) => null //implementation is irrelevant
const TextSelect:Select<string> = (props) => null //implementation is irrelevant
In this scenario, I aim to achieve something similar to the following:
type Filter<V = unknown > = {
component: Select<V>,
transformer: (value: V) => string
};
const filters:Array<Filter> = [
{
component: PersonSelect,
transformer: (selected) => selected.name //the type of `selected` should be inferred as `Person`
},
{
component: TextSelect,
transformer: (selected) => selected //the type of `selected` should be inferred as `string`
}
]
Potential Solution
To address the situation described above, the following approach can be adopted:
const personFilter:Filter<Person> = {
component: PersonSelect,
transformer: (selected) => selected.name
}
const textFilter:Filter<string> = {
component: TextSelect,
transformer: (selected) => selected
}
const filters = [personFilter, textFilter];
However, I am interested in finding a solution that does not require explicitly defining the type for each filter object. Additionally, since the generic `V
` type can vary, utilizing a union of all conceivable combinations is not feasible. Are there alternative approaches available?