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