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

rbt*_*tmr 8 typescript redux

const submitted = useSelector((state) => state.post.submitted)
Run Code Online (Sandbox Code Playgroud)

对于上述 at 状态。我收到错误:

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

这是如何固定的?

我有简单的切片+存储:

const submitted = useSelector((state) => state.post.submitted)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我在 Javascript 上没有遇到这种类型的错误,但在 TS 中会弹出?如果需要的话,需要声明什么类型的类型?

phr*_*hry 14

您应该遵循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
Run Code Online (Sandbox Code Playgroud)
//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
Run Code Online (Sandbox Code Playgroud)


Dav*_*han 6

useSelector是泛型,无法确定state是什么类型,因此默认为unknown. 您需要为 state 提供一个与 的形状相匹配的类型注释initialState,因此您需要将其从切片定义中删除。

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