2017-04-14 148 views
1

在我的角2我使用ngrx並有一些行動和減速器。動作例如:Typescript v2.2.2聯合類型使得錯誤(TS2339)

import { Action } from '@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; 

所以,有些動作具有有效載荷,其他 - 不,和Actions是聯合類型,它可以是ActionOneActionTwo。但在我減速器我有一個錯誤:Property 'payload' does not exist on type 'Actions' Property 'payload' does not exist on type 'ActionTwo'.

減速是這樣的:

export function reducer(state = initialState, action: Actions): IState { 
    switch (action.type) { 

    case actions.actionTypes.ACTION_1: { 
     return Object.assign({}, state, { 
     data: action.payload, 
     }); 
    } 

    case ... 
    } 
} 

我更新版本的打字原稿從2.0.32.2.2後得到這個錯誤。 那麼,有沒有方法可以修復錯誤,而無需將有效載荷應用於每個動作?這種情況可能是tsconfog.json有一些選項嗎?

回答

1

你可以在命名空間而不是字典中聲明常量。這允許ACTION_1和ACTION_2採用字面類型,這是區分聯合工作的基礎。

export namespace actionTypes { 
    export const ACTION_1 = 'Action 1'; // <-- type of ACTION_1 is 'Action 1' in TS 2.1+ 
    export const ACTION_2 = 'Action 2'; 
}; 

的每個class需要的type爲恆定的,否則的type類型將是string代替文本類型。

export class ActionOne implements Action { 
    public readonly type = actionTypes.ACTION_1; // <-- note the `readonly` 
    constructor(public payload: any) { } 
} 

export class ActionTwo implements Action { 
    public readonly type = actionTypes.ACTION_2; 
} 

ACTION_ONE: type('Action one')圖案自打字稿2.1 /角4.已棄用通過NGRX開發商參見https://github.com/ngrx/example-app/pull/88#issuecomment-272623083信息。

+0

'type()'不是來自打字稿,它是用於ngrx的util函數 –

+0

@qweasd檢查更新。 – kennytm

-2

你知道這是哪個操作此開關盒內這樣你就可以轉換爲相應的一個:

case actions.actionTypes.ACTION_1: { 
    return Object.assign({}, state, { 
     data: (action as ActionOne).payload, 
    }); 
} 

編譯器顯然是正確的工會結果只具有共享的性質的類型,​​不是其中之一。

+0

我想知道爲什麼人們不喜歡答案。它確實解決了問題,而且很容易。 –

相關問題