Set type for useState React hook with TypeScript
Question:
How to set type for useState React hook with TypeScript? Answer:
interface IPerson {
firstName: string,
lastName: string,
age: number
}
const [person, setPerson] = useState<IPerson>({firstName: 'John', lastName: 'Doe', age: 33,});
Description:
If you use TypeScript in your React project then you probably already see the following error:
TS2345: Argument of type '...' is not assignable to parameter of type 'SetStateAction<never[]>'
To solve this problem you can add type notation as React.useState
uses a generic
Reference:
TypeScript Object types reference
Share "How to set type for useState React hook with TypeScript?"
Related snippets:
Tags:
useState type, TypeScript type for useState hook, type notation, React.useState Technical term:
Set type for useState React hook with TypeScript