I am new to Typescript.
I have following 4 interfaces :
export interface MyAction<T = any> {
type: T
}
export interface MyAnyAction extends MyAction {
[extraProps: string]: any
}
export interface MyAnyAnyAction extends MyAnyAction{
}
export interface ITestDispatch<A extends MyAction = MyAnyAction> {
<T extends A>(action: T): T
}
I want to create a function of type "ITestDispatch".
I could not understand why TS compiler is throwing error for the below function :
const TestDispatch1Func: ITestDispatch1<MyAnyAction> = (action: MyAnyAnyAction): MyAnyAnyAction => {
let obj: MyAnyAnyAction = {
type: 'skdw',
da: 20
};
return obj;
}
I am getting the below error on "TestDispatch1Func" :
Type '(action: MyAnyAnyAction) => MyAnyAnyAction' is not assignable to type 'ITestDispatch<MyAnyAction>'. Type 'MyAnyAnyAction' is not assignable to type 'T'. 'MyAnyAnyAction' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'MyAnyAction'.
Thanks for clearing my doubt.
This is because the interface
ITestDispatchmeans that the function can take an action of any subtype ofA, so it's conflicting with the types declaration & return type of the functionTestDispatch1Funcwhich is limited toMyAnyAnyAction. The interface is accepting any subtype of A, while the implementation is accepting only 1 subtype.For instance if you had another interface
The definition
ITestDispatch1<MyAnyAction>allows you to callTestDispatch1Func(action: AnotherAction)sinceAnotherAction extends MyAnyAction, but that would obviously conflict with the function defnition expecting onlyMyAnyAnyAction.There are 3 solutions here
TS Playground here