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[]);
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[]);
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[]);
As far as the compiler is concerned: No
But to a reader of the code:
const [guessedLetters, setGuessedLetters] = useState<string[]>([]);