1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptでuseStateに型をつけるべき理由

Posted at

はじめに

React × TypeScriptでSupabaseのデータを扱っているとき、
コード補完が出ずに困った 経験はありませんか?

実はこれ、TypeScriptが「型情報のない変数は中身が何でもOK」と判断してしまうため、プロパティ補完が効かなくなっているのが原因です。

問題

const [spots, setSpots] = useState([]);

この書き方だと、TypeScriptは
spots を「中身が何でもOKな any[]」と判断してしまう。
そのため、spot. と打ってもプロパティ候補が出ない。

解決法

type Spot = {
  id: number;
  name: string;
  wifi: boolean;
  power: boolean;
  voice: boolean;
};

const [spots, setSpots] = useState<Spot[]>([]);

→ spot. と打つと補完が出て、
コードの書き間違いも防げるようになった

まとめ

useStateに型をつけるだけで、
補完が効く&安全にデータを扱えるようになる。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?