简体   繁体   English

使用 typescript 编写减速器。 我该如何纠正错误?

[英]Writing Reducer using typescript. How can I correct the error?

I use typescript, react, redux, typessafe-actions.我使用 typescript,反应,redux,typessafe-actions。

I have this error.我有这个错误。

No overload matches this call.没有重载匹配此调用。 Overload 1 of 2, '(...items: ConcatArray[]): List[]', gave the following error. Overload 1 of 2, '(...items: ConcatArray[]): List[]',给出了以下错误。 Argument of type '{ id: number; '{ id: number; 类型的参数name: string |名称:字符串 | undefined;不明确的; email: string | email:字符串 | undefined;不明确的; gender: string |性别:字符串 | undefined;不明确的; }' is not assignable to parameter of type 'ConcatArray'. }' 不可分配给“ConcatArray”类型的参数。 Object literal may only specify known properties, and 'id' does not exist in type 'ConcatArray'.ts(2769) Object 文字只能指定已知属性,并且 'id' 不存在于类型 'ConcatArray'.ts(2769)

This is error code.这是错误代码。

id: Math.max(...state.map((todo) => todo.id)) + 1,

I modified the id type to correct the error, but the error cannot be solved.我修改了id类型来更正错误,但是无法解决错误。 How should I fix it?我应该如何解决它?

// <Types.d.ts>
    export interface PersonType {
      id?: number;
      name?: string;
      email?: string;
      gender?: string;
    }

// <PeopleReducers.ts>

    import { ActionType, createAction, createReducer } from "typesafe-actions";
    import { PersonType } from "../../types";
    
    export const ADD_LIST = "people/ADD_LIST";
    export const DELETE_LIST = "people/DELETE_LIST";
    
    export const addList = createAction(
      ADD_LIST,
      ({ id, name, email, gender }: PersonType) => ({
        id,
        name,
        email,
        gender,
      })
    )();
    export const deleteList = createAction(DELETE_LIST, ({ id }) => ({
      id,
    }))();
    
    const actions = { addList, deleteList };
    type ListAction = ActionType<typeof actions>;
    
    export type List = {
      id: number;
      name: string;
      email: string;
      gender: string;
    };
    type ListState = List[];
    
    const initialState: ListState = [];
    
    const list = createReducer<ListState, ListAction>(initialState, {
      [ADD_LIST]: (state, { payload: { name, email, gender } }) =>
        state.concat({
          id: Math.max(...state.map((todo) => todo.id)) + 1, // This is error line
          name,
          email,
          gender,
        }),
      [DELETE_LIST]: (state, { payload: { id } }) =>
        state.filter((item) => item.id !== id),
    });
    export default list;
//  <Row component>


    import { PersonType } from "../types";
    
    export default function Row({ name, email, gender }: PersonType) {
      return (
        <>
          <p>{name}</p>
          <p>{email}</p>
          <p>{gender}</p>
        </>
      );
    }

Problem: Possibly Undefined Properties问题:可能未定义的属性

The error is confusingly worded, but the issue is that the properties name , email , and gender are defined as optional in the payload from the action creator ( PersonType ).该错误措辞令人困惑,但问题是属性nameemailgender在来自操作创建者 ( PersonType ) 的有效负载中定义为可选。 When you concat an item to the state List[] it must be a complete List object.当您将项目连接到concat List[]时,它必须是完整的List object。 So these optional properties are a problem.所以这些可选属性是个问题。

Bad Solution: Set Defaults糟糕的解决方案:设置默认值

You can prevent errors by defaulting all of the payload properties to an empty string.您可以通过将所有payload属性默认为空字符串来防止错误。

[ADD_LIST]: (state, { payload: { name = "", email = "", gender = "" } }) =>
  state.concat({
    id: Math.max(...state.map((todo) => todo.id)) + 1,
    name,
    email,
    gender
  }),

Good Solution: Fix the Action好的解决方案:修复操作

It is always better to tackle the problem as the source.解决问题的根源总是更好。 Why are we allowing these required properties to be optional in the action creator?为什么我们允许这些必需的属性在动作创建器中是可选的? We want to require all properties except that we don't want an id because we are going to create that ourselves.我们想要要求所有属性,除了我们不想要一个id因为我们将自己创建它。

export const addList = createAction(
  ADD_LIST,
  ({ name, email, gender }: Omit<List, "id">) => ({
    name,
    email,
    gender
  })
)();

or simply:或者简单地说:

export const addList = createAction(
  ADD_LIST,
  (payload: Omit<List, "id">) => payload
)();

Now your reducer can stay the same as it was before.现在你的减速器可以和以前一样了。 The errors will be gone because the required properties are known to be present in the action payload .错误将消失,因为已知所需的属性存在于操作payload中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据 typescript,react childNodes 没有 offsetWidth。我怎样才能取悦 typescript? - react childNodes do not have offsetWidth according to typescript. How can I please typescript? 我正在努力用打字稿完成redux。 如何在这些操作中调整类型 - I'm working to complete redux with typescript. How can I adjust type what I want in these actions 如何使用 Typescript 将多个参数传递给 redux 减速器? - How can I pass multiple parameters to a redux reducer with Typescript? 如何更正 typescript 错误? (道具类型库) - How can I correct the typescript error? (prop-Types library) 在反应 typescript 中将道具传递给孩子的正确类型。 错误 ts(2322) - Correct types to pass props down to children in react typescript. Error ts(2322) 如何检查 typescript 中的类型。 不工作的例子 - how to check type in typescript. instance of not working 我如何使用Reducer将对象添加到数组中 - How can i add objects into array using reducer Reactjs - 使用 typescript 时 createStore 无法识别减速器 - Reactjs - createStore can't recognize the reducer when using typescript 谷歌地图反应与 TypeScript。 参数错误 - Google-Maps-React with TypeScript. Error with parameters 不能在打字稿上分配减速器? - can't assign reducer on typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM