angular - Typescript v2.2.2 union type makes error (TS2339) -


in angular 2 use ngrx , have actions , reducers. example of actions :

import { action } '@ngrx/store';  export const actiontypes = {   action_1: type('actions 1'),   action_2: type('actions 2'), };  export class actionone implements action {   public type = actiontypes.action_1;    constructor(public payload: any) { } }  export class actiontwo implements action {   public type = actiontypes.action_2; }  export type actions   = actionone   | actiontwo; 

so, actions has payload, others - no, , actions union type, can actionone or actiontwo. in me reducer have error: property 'payload' not exist on type 'actions' property 'payload' not exist on type 'actiontwo'.

reducer this:

export function reducer(state = initialstate, action: actions): istate {   switch (action.type) {      case actions.actiontypes.action_1: {       return object.assign({}, state, {         data: action.payload,       });     }      case ...   } } 

i got error after updating typescript version 2.0.3 2.2.2. so, there way fix error without putting payload every action? may there option tsconfog.json case?

you declare constants in namespace, instead of dictionary. allows action_1 , action_2 take literal type, essential discrimated union work.

export namespace actiontypes {     export const action_1 = 'action 1';  // <-- type of action_1 'action 1' in ts 2.1+     export const action_2 = 'action 2'; }; 

the type of each class needs constant, otherwise type of type string instead of literal type.

export class actionone implements action {     public readonly type = actiontypes.action_1;   // <-- note `readonly`     constructor(public payload: any) { } }  export class actiontwo implements action {     public readonly type = actiontypes.action_2; } 

the action_one: type('action one') pattern has been deprecated ngrx developers since typescript 2.1 / angular 4. see https://github.com/ngrx/example-app/pull/88#issuecomment-272623083 information.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -