gpt4 book ai didi

typescript - (参数) state : unknown Object is of type 'unknown' . redux TS

转载 作者:行者123 更新时间:2023-12-02 01:37:56 24 4
gpt4 key购买 nike

const submitted = useSelector((state) => state.post.submitted)

对于上面的状态。我得到错误:

(参数)状态:未知对象的类型为“未知”。

这是如何解决的?

我有简单的 slice + store:

import { createSlice } from '@reduxjs/toolkit'

export const postSlice = createSlice({
name: 'post',
initialState: {
shared: false,
submitted: false,
},
reducers: {
setShared: (state, action) => {
state.shared = action.payload
},
setSubmitted: (state, action) => {
state.submitted = action.payload
},
},
})

export const { setShared, setSubmitted } = postSlice.actions
export default postSlice.reducer

import { configureStore, combineReducers } from '@reduxjs/toolkit'

//import slice as reducer
import postReducer from './features/postSlice'

const rootReducer = combineReducers({
//combine all reducers
post: postReducer,
})

export const store = configureStore({
reducer: rootReducer,
})

虽然在 TS 中弹出,但我在 Javascript 上没有遇到此类错误?如果需要,需要为此声明什么类型?

最佳答案

useSelector 是泛型,无法确定state 是什么类型,所以默认为unknown。您需要为状态提供一个与 initialState 的形状匹配的类型注释,因此您需要将其从切片定义中分离出来。

  1. 定义接口(interface)(如果您愿意,也可以使用类型/类型别名)
interface MyState {
shared: boolean
submitted: boolean
}
  1. 类型转换 initialState,或使用中间类型变量(我认为这是可选的,但查看文档示例表明这是可能的):
  // ...
initialState: {
shared: false,
submitted: false,
} as MyState,
// ...
  1. 为回调添加类型注解
const submitted = useSelector((state: MyState) => state.post.submitted)

关于typescript - (参数) state : unknown Object is of type 'unknown' . redux TS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72039694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com