DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

Why you should type useState in TypeScript

Introduction

Have you ever had trouble with no code completion when working with Supabase data using React and TypeScript?

This is because TypeScript assumes that "variables without type information can have anything" and property completion doesn't work.

Problem

const [spots, setSpots] = useState([]);
Enter fullscreen mode Exit fullscreen mode

When written this way, TypeScript interprets spots as "any[]," meaning that anything is allowed.
As a result, no property suggestions appear when you type spot.

Solution

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

const [spots, setSpots] = useState<Spot[]>([]);
Enter fullscreen mode Exit fullscreen mode

→ Typing "spot." results in completion,
preventing code typos.

Summary

By simply adding a type to useState,
you can get completion and safely handle data.

Top comments (0)