I was was curious how Redux Toolkit works under the hood and tried to replicate a basic implementation. But I ran into an issue regarding the indexable type AnyAction and the type PayloadAction that has a defined property called payload.
The builder.addCase function expects a reducer function as the second parameter. This reducer in turn has 2 parameters state & action. The action parameter defaults to AnyAction. The moment I manualy set the type of action to PayloadAction<P> an error pops up regarding the missing property payload in type Action<string>.
I cannot seem to get my head around it and was hoping someone could help me out and explain to me why this does not work.
export interface Action<T extends any = string> {
type: T
}
export interface AnyAction extends Action {
[extraProps: string]: any
}
export interface PayloadAction<P = any> extends Action {
payload: P
}
const builder = {
addCase(
typeOrActionCreator: string, reducer: <A extends Action = AnyAction>(state: any, action: A) => void
) {
return builder
}
}
builder.addCase('test', (state, action: PayloadAction<number>) => {
action.payload
}).addCase('tester', (state, action) => {
action
})