用打字稿打字Redux Store

时间:2020-09-07 15:28:19

标签: javascript reactjs typescript redux

以下是动作创建者的类型:

    export type Calculation = {
      type: string;
    };
    
    export type AddAndSubtract = {
      type: string;
      value: number;
    };
    
    export type GetUserInput = {
      type: string;
      value: HTMLTextAreaElement;
    };

export type DispatchActions = Calculation | GetUserInput | AddAndSubtract;

这是商店:

export const rootReducer = (state = initialState, action: DispatchActions) => {
  switch (action.type) {
    case "INCREMENT":
      return { ...state, count: state.count + 1 };
    case "DECREMENT":
      return { ...state, count: state.count - 1 };
    case "ADD_5":
      return { ...state, count: state.count + action.value };
    case "SUBTRACT_5":
      return { ...state, count: state.count - action.value };
    case "RESET":
      return { ...state, count: action.value };
    case "GET_USER_INPUT":
      return { ...state, userInput: action.value };
    case "MULTIPLY":
      return {
        ...state,
        count: state.count * state.userInput,
      };
    default:
      return state;
  }
};

但是打字稿显示错误:类型“ DispatchActions”上不存在属性“值”。属性“值”在“计算”类型上不存在。我该如何解决?

3 个答案:

答案 0 :(得分:1)

无需在此处使用联合类型。您只需要创建单个类型DispatchAction:

export type DispatchAction = {
      type: string;
      value: number | HTMLTextAreaElement;
}

export const rootReducer = (state = initialState, action: Partial<DispatchAction>) =>

OR

export type DispatchAction = {
      type: string;
      value?: number | HTMLTextAreaElement;
}

export const rootReducer = (state = initialState, action: DispatchAction) => ...

答案 1 :(得分:1)

除上述评论外。这也可以!

在Calculation中添加值键,您使用的是联合类型。

bootJar {
    layered {
        application {
            intoLayer("spring-boot-loader") {
                include("org/springframework/boot/loader/**")
            }
            intoLayer("application")
        }
        dependencies {
            intoLayer("module-dependencies") {
                include("com.example:*:*")
            }
            intoLayer("dependencies")
        }
        layerOrder = [ "dependencies", "spring-boot-loader", "module-dependencies", "application" ]
    }
}

阅读https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html以获得更多帮助和错误原因!

答案 2 :(得分:0)

正如其他人所指出的那样,问题出在您如何使用工会。在撰写本文时,Typescript没有任何办法知道您正在传递的联合中哪些可能的类型,因此必须假定它可能是其中的任何一种。例如,通过键入这样的操作完全正确:

const badAction:Calculation = {
  type: “SUBTRACT_5”
}

在运行时无法使用您的代码-这正是TS告诉您的。您可以通过像上面的答案所示的弱类型来处理。或者,您可以使用字符串文字来提供更强的联合输入,如in the Redux docs.

所述