LoginSignup
4
1

More than 3 years have passed since last update.

Property 'hogehoge' does not exist on type 'DefaultRootState'を解決する【React/Redux】

Posted at

はじめに

React+ReduxをTypeScriptで実装する中で、useSelector構文内で発生したエラーを解決します。

エラー内容

Property 'hogehoge' does not exist on type 'DefaultRootState'

hogehogeは、型DefaultRootStateに存在していないよというエラーです。

該当箇所

下記のcountの箇所でエラーが発生します。

Count.tsx

//省略

const Count = () => {
  const count = useSelector((state) => state.count)

  //省略

}

解決方法

結論:stateの型定義を行いましょう!

1.RootStateという名前でstateの型を定義する
ここではcountだけですが、他にstoreで管理する値がある場合は、それを列挙します。
※RootStateという命名は何でも良いです

store.ts

// 省略

export type RootState = {
 count: number
}

// 省略

2.useSelector関数の引数stateにRootState(型)を定義する

Count.tsx

//省略
//①RootStateをインポートする
import { RootState } from 'store'

const Count = () => {
  //②stateをRootStateで型定義する
  const count = useSelector((state: RootState) => state.count)

  //省略

}

これで解決!

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1