gpt4 book ai didi

typescript - 具有枚举类型问题的 Ngrx 操作

转载 作者:行者123 更新时间:2023-12-04 03:02:38 25 4
gpt4 key购买 nike

嘿,我正在尝试构建 actions/reducers/etc 但我遇到了一个令人沮丧的 TypeScript 问题。我正在尝试对操作类型使用字符串枚举,但无法使用以下内容进行编译:

enter image description here

代码如下:

import { Action, ActionReducerMap } from '@ngrx/store';

export enum AnnoSetsTypes {
ADD_MANY = '[AnnoSets] Add Many',
RESET = '[AnnoSets] Reset',
}

export class AddMany implements Action {
readonly type = AnnoSetsTypes.ADD_MANY;

constructor(public annoSets: any[]) { }
}

export class Reset implements Action {
readonly type = AnnoSetsTypes.RESET;
}

export type AnnoSetsAction = AddMany | Reset;

export interface IAnnoSetsState {
annoSets: any[];
}

export function annoSetsReducer(
state: IAnnoSetsState = { annoSets: [] },
action: AnnoSetsAction
): IAnnoSetsState {
switch (action.type) {
case AnnoSetsTypes.ADD_MANY:
return { annoSets: [...action.annoSets] };
case AnnoSetsTypes.RESET:
return { annoSets: [] };
default:
return state;
}
}

export interface State {
annoSets: IAnnoSetsState;
}

export const reducers: ActionReducerMap<State> = { // <-- COMPILE ERROR HERE
annoSets: annoSetsReducer,
};

我目前使用的是:

  • typescript 2.6.2
  • Ngrx 4.1.1

这是一个经过精简的 repo:https://github.com/cha55son/ngrx-action-type-issue

一些注意事项。我不想将枚举转换为字符串,因为它会导致类型缩小在 switch 语句中失败。它在这里似乎也工作得很好:https://github.com/ngrx/platform/blob/master/example-app/app/core/actions/layout.ts#L3所以我假设我需要设置一些 TypeScript 配置。据我所知,代码应该足够了。任何帮助,将不胜感激。谢谢!

最佳答案

tsconfig.json 中,设置 strict: true 也设置了 strictFunctionTypes: true,这会导致错误。显式禁用 strictFunctionTypes 应该清除它。
{
“编译器选项”:{
“源 map ”:真实的,
“声明”:假的,
"moduleResolution": "节点",
“emitDecoratorMetadata”:真实的,
“experimentalDecorators”:真实的,
“库”:[
"es2017",
“统治”
],
“目标”:“ES5”,
“模块”:“es2015”,
“严格”:真实,
“strictFunctionTypes”:假
},
“compileOnSave”:真
}

关于typescript - 具有枚举类型问题的 Ngrx 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47818928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com