How do I do something simple like this in Typescript?
const [text, setText] = useState("");
I'm getting a lot of errors, and I don't know how to fix them.
Parameter 'text' implicitly has an 'any' type.ts(7006)
Parameter 'setText' implicitly has an 'any' type.ts(7006)
'useState', which lacks return-type annotation, implicitly has an 'any' return type.ts(7010)
CodePudding user response:
As Jared Smith suggested, you just need to install the @types/react
package for example with
yarn add -D @types/react
or
npm install --save-dev @types/react
The usage is straightforward if your default value is of the same type as the actual value, but if you have multiple possible types than you have to specify the type yourself. F.e. if the state can be null
or a string:
const [value, setValue] = useState<string | null>(null);
without the <string | null>
type annotation you will get an error when you try to set a string as a value with
setValue("some string");