I'm encountering an issue with a TypeScript decorator related to typing function parameters in a Redux context. The decorator in question is @OnAction
, which intercepts actions based on their type
.
My goal is to specify the type for the decorator so that it requires a function parameter corresponding to the action type. For example, using
@OnAction('history/modal/toggle')
, I expect the decorator to require a function with a parameter action: HistoryModalToggleAction
.
However, I am running into a compile error with my current codebase involving this decorator.
// Sample.ts
export interface HistoryModalReducerProps {
visible: boolean;
otherStuff: string;
}
export interface HistoryModalToggleAction extends Action<'history/modal/toggle'> {
visible: boolean;
}
export type StoreAction = HistoryModalToggleAction | Action<'otherAction1'> | Action<'otherAction2'>;
export class Sample {
@OnAction('history/modal/toggle')
onToggle(state: Readonly<HistoryModalReducerProps>, action: HistoryModalToggleAction): Readonly<HistoryModalReducerProps> {
if (!action.visible)
return state;
else
return {
...state,
visible: true
};
}
}
// OnAction.ts
type RestrictedMethod<A extends StoreAction> = (
prototype: any,
key: string,
descriptor: TypedPropertyDescriptor<(
state: any,
action: A
) => any>
) => void;
export function OnAction<A extends StoreAction>(type: A['type']): RestrictedMethod<A> {
const restrictedMethod: RestrictedMethod<A> = (prototype, key, descriptor) => {
// ...
};
return restrictedMethod;
}
The compile error indicates that my function expects StoreAction
while receiving HistoryModalToggleAction
. Despite being compatible types, the error persists. My TypeScript version is 3.5.3
.
I appreciate any assistance or guidance on resolving this issue.