TypeScript React - useReducer 与接口中的对象数组

TypeScript React - useReducer with Array of Objects in Interface

我创建了以下组件:

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<any>, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error. Argument of type '(state: typeof initialState, action: ACTION_TYPE) => { users: { id: number; }[]; }' is not assignable to parameter of type 'ReducerWithoutAction<any>'. Overload 2 of 5, '(reducer: (state: { users: never[]; }, action: ACTION_TYPE) => { users: { id: number; }[]; }, initialState: never, initializer?: undefined): [never, Dispatch<ACTION_TYPE>]', 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 的类型 - 但这也不起作用。

"typescript": "^4.3.5"。您需要使用类型断言为 state.users:

指定 User[] 类型
const initialState = {
  users: [] as User[],
};

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