2017-02-20 59 views
2

我想基於在https://github.com/ngrx/example-app/找到的示例應用程序構建一個Angular 2/ngrx應用程序。我出口動作類型爲區分聯合Typescript歧視的工會類型不被識別

export const ActionTypes = { 
    QUERY: type('[Games] Query'), 
    QUERY_COMPLETE: type('[Games] Query Complete'), 
    INVALIDATE: type('[Games] Invalidate'), 
    SELECT: type('[Games] Select'), 
    LOAD_NEXT_PAGE: type('[Games] Load Next Page'), 
    LOAD_NEXT_PAGE_COMPLETE: type('[Games] Load Next Page Complete'), 

}; 

export class QueryAction implements Action { 
    type = ActionTypes.QUERY; 

    constructor(public payload: string) {} 
} 

export class QueryCompleteAction implements Action { 
    type = ActionTypes.QUERY_COMPLETE; 

    constructor(public payload: Game[]) {} 

} 

export class LoadNextPageCompleteAction implements Action { 
    type = ActionTypes.LOAD_NEXT_PAGE_COMPLETE; 

    constructor(public payload: Game[]) {} 
} 

export class LoadNextPageAction implements Action { 
    type = ActionTypes.LOAD_NEXT_PAGE; 

    constructor() {} 
} 

export class InvalidateAction implements Action { 
    type = ActionTypes.INVALIDATE; 

    constructor(){} 
} 

export class SelectAction implements Action { 
    type = ActionTypes.SELECT; 

    constructor(public payload: number) {} 
} 

export type Actions = QueryAction | QueryCompleteAction | InvalidateAction | SelectAction | LoadNextPageAction | LoadNextPageCompleteAction; 

而且通過這些來減速功能,在辨別基於type屬性如下:

export function reducer(state = initialState, action: game.Actions): State { 
    switch (action.type) { 
    case game.ActionTypes.LOAD_NEXT_PAGE: 
    case game.ActionTypes.QUERY: { 
     return Object.assign({}, state, {loading: true}); 
    } 
    case game.ActionTypes.QUERY_COMPLETE: { 
     return { 
     games: action.payload, 
     offset: action.payload.length, 
     loading: false, 
     selectedGameId: null 
     } 
    } 
    case game.ActionTypes.LOAD_NEXT_PAGE_COMPLETE: { 
     return { 
     games: [...state.games, ...action.payload], 
     offset: state.offset + action.payload.length, 
     loading: false, 
     selectedGameId: state.selectedGameId 
     } 
    } 
    case game.ActionTypes.SELECT: { 
     return Object.assign({}, state, {selectedGameId: action.payload}); 
    } 
    default: { 
     return state; 
    } 
    } 
} 

這失敗,出現錯誤編譯(其他中錯誤)

Type 'string | number | Game[]' is not assignable to type 'Game[]'. 
Type 'string' is not assignable to type 'Game[]'. 
Property 'length' does not exist on type 'string | number | Game[]'. 
Property 'length' does not exist on type 'number' 

我是否做錯了或不瞭解歧視工會的工作方式?我的理解是,switch語句應該縮小可能的類型action.payload,以保證它是正確的類型。它似乎與聯盟中所有成員的類型相比,而不是隻有匹配類型的成員。

該項目使用的打字稿v2.1.6

+0

您的代碼看起來很好,與我使用ngrx示例一樣。檢查您的導入語句以查找「遊戲」操作。確保它指向正確的操作文件。 –

回答

3

this github issuepull request

與打字稿2.1+重大更改開始,字符串字面 類型總是拉大到字符串,除非分配給一成不變的常量 變量或只讀屬性。這意味着像開關 (action.type)語句利用歧視聯盟停止工作 與當前的示例應用程序模式。

+0

D'oh!我曾搜索過github的問題,但並不確定要使用哪些搜索條件。謝謝! – rabble