我想基于在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
您的代码看起来很好,与我使用ngrx示例一样。检查您的导入语句以查找“游戏”操作。确保它指向正确的操作文件。 –