【发布时间】:2021-03-10 07:06:53
【问题描述】:
我正在开发一个包含 React、Redux 和 TypeScript 的项目。
由于 TypeScript 的类型限制,我无法弄清楚如何设置初始状态。有人知道如何设置类型吗?
为简单起见,我将所有内容压缩在一个文件中,稍后将分成单独的文件。
state/index.ts
import { Notes } from '@material-ui/icons'
import { createStore, combineReducers } from 'redux'
// Types
type Note = {
title: string
description: string
}
type NoteState = {
notes: Array<Note>
}
type NoteAction = {
type: string
payload: Note
}
type CountState = {
count: number
}
type CountAction = {
type: string
payload: number
}
// Actions
const ADD_NOTE = 'ADD_NOTE'
const addNote: (note: Note) => NoteAction = (n) => ({ type: ADD_NOTE, payload: n })
const INCREMENT = 'INCREMENT'
const increment: (n: number) => CountAction = (n) => ({ type: INCREMENT, payload: n + 1 })
// Reducer
const noteReducer: (s: NoteState, a: NoteAction) => NoteState = (s = { notes: [] }, a) => {
switch (a.type) {
case ADD_NOTE:
return { notes: [...s.notes, a.payload] }
default:
return s
}
}
const countReducer: (s: CountState, a: CountAction) => CountState = (s = { count: 0 }, a) => {
switch (a.type) {
case INCREMENT:
return { count: a.payload }
default:
return s
}
}
const rootReducer = combineReducers({
notes: noteReducer,
counter: countReducer,
})
type RootState = ReturnType<typeof rootReducer>
// Store
const state = createStore(rootReducer({ notes: [], counter: 0 }, null))
错误 初始化状态对象时,IDE报错:
No overload matches this call.
Overload 1 of 2, '(reducer: Reducer<unknown, Action<any>>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<unknown, Action<any>>', gave the following error.
Argument of type 'CombinedState<{ notes: never; counter: never; }>' is not assignable to parameter of type 'Reducer<unknown, Action<any>>'.
Type 'CombinedState<{ notes: never; counter: never; }>' provides no match for the signature '(state: unknown, action: Action<any>): unknown'.
Overload 2 of 2, '(reducer: Reducer<unknown, Action<any>>, preloadedState?: {} | undefined, enhancer?: StoreEnhancer<unknown, {}> | undefined): Store<unknown, Action<any>>', gave the following error.
Argument of type 'CombinedState<{ notes: never; counter: never; }>' is not assignable to parameter of type 'Reducer<unknown, Action<any>>'.ts(2769)
我需要在 createStore 函数中设置 App State。因为稍后会有一个函数从本地存储中检索 App State 并通过 createStore 方法传递。但我想先完成这项工作。有人有使用 Redux + TypeScript 的经验吗?
【问题讨论】:
-
你能不能试试, const initialData: RootState = { notes: [], counter: 0 }; const state = createStore(rootReducer(initialData), null))
-
我认为,您不应该将任何数据传递给 rootReducer。
-
const initialData: RootState = { notes: [], counter: 0 }; const state = createStore(rootReducer)
-
我试过了,但我得到了一个我还不明白的错误。它与 IDE 抱怨 InitialData 中的值类型为
never有关。Type 'never[]' is not assignable to type 'never'.ts(2322) index.ts(55, 5): The expected type comes from property 'notes' which is declared here on type 'CombinedState<{ notes: never; counter: never; }>'
标签: reactjs typescript redux react-redux state