typescript (参数)状态:unknown对象的类型为“unknown”,还原TS

dzhpxtsq  于 2023-05-08  发布在  TypeScript
关注(0)|答案(3)|浏览(544)
const submitted = useSelector((state) => state.post.submitted)

在国家上面。我收到错误:
(参数)状态:unknown对象的类型为“unknown”。
这是如何解决的?
简单的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,
})

我没有得到这种类型的错误的Javascript,虽然弹出在TS?如果需要的话,需要声明什么类型的类型?

xkrw2x1b

xkrw2x1b1#

您应该遵循TypeScript快速入门指南并设置正确类型的钩子:

// store.ts

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
//hooks.ts

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
xriantvc

xriantvc2#

useSelector是泛型,不能确定state是什么类型,所以默认为unknown。你需要给予state一个与initialState的形状匹配的类型注解,所以你需要把它从切片定义中分离出来。
1.定义接口(如果愿意,也可以使用类型/类型别名)

interface MyState {
  shared: boolean
  submitted: boolean
}

1.类型转换initialState,或者使用一个中间类型变量(我认为这是可选的,但看一下文档中的示例表明这是可能的):

// ...
  initialState: {
    shared: false,
    submitted: false,
  } as MyState,
  // ...

1.向回调添加类型注解

const submitted = useSelector((state: MyState) => state.post.submitted)
kqlmhetl

kqlmhetl3#

const generalUserInfo = useSelector((state:return();
执行此操作:状态**:任何**

相关问题