Let's have a following code:
interface Action {
type: string;
}
interface ActionA extends Action {
type: 'A';
payload: number;
}
interface ActionB extends Action {
type: 'B';
payload: string;
}
interface Processor<T extends Action> {
action: T;
process: (action: T) => void;
}
// usage
const actionA: ActionA = { type: 'A', payload: 42 };
const processorA: Processor<ActionA> = {
action: actionA,
process(action) {
// ...
},
};
Now I think that specifying type argument ActionA in const processorA: Processor<ActionA> = ... is redundant as it could be inferred from action: ActionA. Unfortunately Typescript reports error if I write just const processorA: Processor = ....
Is it possible to improve interfaces so that type argument of Processor would be inferred?
Advanced version:
I would also like action field to be of type T | '*'. In that case action parameter of process(action) should be of type Action (or in worst case just any). Is this possible together with above mentioned type parameter inferring?