Home > Net >  Any difference in declaring useState in these two different ways?
Any difference in declaring useState in these two different ways?

Time:12-06

I am new to TypeScript and am wondering is there any difference between using:

  const [guessedLetters, setGuessedLetters] = useState<string[]>([]);

and

  const [guessedLetters, setGuessedLetters] = useState([] as string[]);

CodePudding user response:

They produce identical types.

To support my claim and give you more confidence, here's the type for the useState overload signature that accepts an argument (from the latest commit at the time I write this message):

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

So, whether you supply a type for the generic type parameter or use a type assertion on the argument value, the outcome is the same in this case.

Here's a reproduction of your example in the TypeScript playground, showing the inferred types of the destructured tuple values:

TS Playground

import {useState} from 'react';

const [
  state1,
//^? const state1: string[]
  setState1,
//^? const setState1: Dispatch<SetStateAction<string[]>>
] = useState<string[]>([]);

const [
  state2,
//^? const state2: string[]
  setState2,
//^? const setState2: Dispatch<SetStateAction<string[]>>
] = useState([] as string[]);

CodePudding user response:

As far as the compiler is concerned: No

But to a reader of the code:

  1. The first example is preferable for readability - it's more concise
  2. Additionally, you should try to limit the uses of type assertions until:
const [guessedLetters, setGuessedLetters] = useState<string[]>([]);
  • Related