我正在尝试将我的 angular 2 应用程序迁移到 angular 4 和 ngrx 4。
我正在处理一个奇怪的打字稿编译问题,这是我在此更新之前没有遇到的。我在离线环境中工作,所以我不能在这里分享确切的代码。
我在网上寻找问题,我能找到的最接近的问题是这个问题: 关于有效负载类型 的问题这个问题中的代码在某种程度上类似于我试图做的事情,但不同的是我从动作中删除了 ActionTypes 对象(这是该问题的建议答案)但它没有解决我的编译错误。
我不能把我要处理的确切代码放在这里,但我的代码完全基于 github 上的 ngrx 示例 ngrx 官方示例
让我们看一下 book reducer 和 book actions book actions book reducer的例子
我的代码基本相同,当我尝试从操作中获取有效负载时,每个减速器案例(在 switch 案例中)都会发生错误,它告诉我如下信息:
Type 'string | Book | Book[]' is not assignable to type 'Book'. Type 'string' is not assignable to type 'Book'.
(在我的代码中,我有不同的类,而不是 Book,但它的想法几乎相同)
现在我通过从 A | 转换动作类型来解决错误。乙| B 为 switch 中 case 对应的具体动作类型(使用 as typescript 关键字)。这个解决方案感觉很糟糕和hacky,我想知道是否有更好的解决方案。
我使用的版本:打字稿:2.4.1(我怀疑它可能连接到不使用与我相同的更新打字稿版本的ngrx示例)ngrx@store:4.0.3 ngrx@core:1.2.0 angular:(最新为17.9.17,有很多包里面有角度,我认为这个错误使用哪个角度并不重要,但我说这只是为了安全起见)打字稿:(2.4.1)(我读了ngrx关于需要升级打字稿的官方迁移文档,所以我这样做了)
更新:由于我得到了一个与我的问题无关的答案并且我被问到,这是我的代码失败的部分(我无法发布确切的帖子,但我手动复制了相关部分):
任务减速器.ts:
import * as MissionActionsFile from "./mission-actions";
export type State = .... // doesnt matter
const initialState: State = // doesnt matter as well
export function reducer(state: State = initialState, action:
MissionActionsFile.Actions): State {
switch(action.type) {
case MissionActionsFile.ADD_SUCCESS:
{
const mission: Mission = action.payload; // This line generates the
// following error:
// Type 'string | number | Mission | MissionRealTime | ...' is not
// assignable
// to type 'Mission'. Type 'string' is not assignable to type 'Mission'
return {}; // This doesnt matter too
}
// There are more cases and a deafult one, but that doesn't matter
}
}
任务-actions.ts:
// I will only give the actual action defenition for AddSuccess and for AddFailed since we are using AddSuccess in the example and
// addFailed is an example where the payload type is string, which according to the error is the problem, though
// there are more action types and other payload types with other classes as the quoted error implies.
export const ADD_SUCCESS: string = "[Mission] AddSuccess";
export const ADD_FAILED: string = "[Mission] AddFailed";
export class AddSuccessAction implements Action {
public readonly type: string = ADD_SUCCESS;
constructor(public payload: Mission) {}
}
export class AddFailedAction implements Action {
public readonly type:string = ADD_FAILED;
constructor(public payload: string) {}
}
// More actions are defined here but im not gonna copy all
...
export type Actions =
AddSuccessAction |
AddFailedAction;
所以总而言之,我确实明白为什么 typescript 认为动作有效负载类型可能是 string | 是有意义的。使命 | ...但是在我基于此的ngrx示例中,似乎打字稿知道在那里推断案例中的特定类型,但对我来说,由于我不理解的原因这不起作用,可能与我有关使用打字稿 2.4.1?不确定,需要帮助