How to Add a Type to useState Hook in TypeScript

Published Feb 3, 2022  ∙  Updated May 2, 2022

How can we add a type to a useState() hook in TypeScript?

Suppose we have an interface User.

interface User {
  id: number,
};

We want to create a state using useState() and apply this interface to the state.

import React, { useState } from "react";
const [user, setUser] = useState<User>({id: 1});

Check out the type in the DefinitelyTyped source.