The following shows the actions classes and the union type. However those actions are not recognized when running the application.
export class Login implements Action {
readonly type = LOGIN;
constructor(
public payload: {
userID: string;
email: string;
token: string;
expirationDate: Date;
}
) {}
}
export class Logout implements Action {
readonly type = LOGOUT;
constructor() {}
}
export class LoginStart implements Action {
readonly type: string = LOGIN_START;
constructor(public payload: { username: string; password: string }) {}
}
export class LoginFail implements Action {
readonly type: string = LOGIN_FAIL;
constructor(public payload: string) {}
}
export type AuthActions = Login | Logout | LoginStart | LoginFail;
When running the application, ng serve gives the following error.
ERROR in src/app/auth/store/auth.reducer.ts:23:16 - error TS2339: Property 'payload' does not exist on type 'AuthActions'.
Property 'payload' does not exist on type 'Logout'.
23 action.payload.userID,
~~~~~~~
src/app/auth/store/auth.reducer.ts:24:16 - error TS2339: Property 'payload' does not exist on type 'AuthActions'.
Property 'payload' does not exist on type 'Logout'.
24 action.payload.email,
~~~~~~~
src/app/auth/store/auth.reducer.ts:25:16 - error TS2339: Property 'payload' does not exist on type 'AuthActions'.
Property 'payload' does not exist on type 'Logout'.
25 action.payload.token,
Could someone please provide a clue on how to resolve this, without changing the constructors?
I followed following threads, but no proper solution was given. Typescript discriminated union type not recognized
As the error message says, the given property (
payload) does not exist onLogout. As a thumb of rule in certain cases, it worths to useActionWithPayload<T>utility type next toAction, because some actions may have payload, some may not.This issue is with the architecture itself, not the implementation.
If you add the given utility type
ActionWithPayload<T>you can use to check if the given instance has the propertypayload.So first what you need is the utility interface:
Then you would need an utility function to check if the given object is an instance of
ActionWithPayload<T>Then you can use it to check if the given instance has the proper property:
and
Ofc, to prettify your code it would be awesome to implement the interface in the classes instead of
Actionwhat is misleading.