【问题标题】:TypeScript React - useReducer with Array of Objects in InterfaceTypeScript React - 接口中带有对象数组的 useReducer
【发布时间】:2021-10-20 15:57:30
【问题描述】:

我创建了以下组件:

import React, {useReducer} from 'react'

type ACTION_TYPE = | {type: 'SET_USER', userId: number} | {type: 'DELETE_USER', userId: number, deleteMessages: boolean}

interface User { 
    id : number; 
    name? : string; 
    surname?: string; 
    hasDiscount?: boolean;
}


const myReducer = (state : typeof initialState, action : ACTION_TYPE) => { 
    switch (action.type) {
        case 'DELETE_USER':
            return {users: [...state.users, {id: action.userId}]}
        default:
            return state;
    }
}

const initialState = {
    users : []
}

const TestingComponent : React.FC = () => { 

    const [state, dispatch] = useReducer(myReducer,initialState)


    return (
<div></div>
    )
}

export default TestingComponent

我的useReducer - No overload matches this call. Overload 1 of 5, '(reducer: ReducerWithoutAction&lt;any&gt;, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error. Argument of type '(state: typeof initialState, action: ACTION_TYPE) =&gt; { users: { id: number; }[]; }' is not assignable to parameter of type 'ReducerWithoutAction&lt;any&gt;'. Overload 2 of 5, '(reducer: (state: { users: never[]; }, action: ACTION_TYPE) =&gt; { users: { id: number; }[]; }, initialState: never, initializer?: undefined): [never, Dispatch&lt;ACTION_TYPE&gt;]', gave the following error. Argument of type '{ users: never[]; }' is not assignable to parameter of type 'never'.ts(2769) 出现错误

虽然我不确定如何解释 - 我也尝试过创建以下界面

interface USER_STATE { 
    users: [User]
}

并在myReducer 中使用它来定义state 的类型——但这也不起作用。

【问题讨论】:

    标签: reactjs typescript types react-hooks use-reducer


    【解决方案1】:

    "typescript": "^4.3.5"。您需要使用类型断言为state.users 指定User[] 类型:

    const initialState = {
      users: [] as User[],
    };
    

    这样typeof initialState 将推断出正确的状态类型。否则,TS 会将typeof initialState 推断为{ users: never[]; } 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2021-06-08
      • 1970-01-01
      相关资源
      最近更新 更多