I\'m migrating a React with TypeScript project to use hooks features (React v16.7.0-alpha), but I cannot figure out how to set typings of the destructured elements.
You could also declare the initial state before and then be able to call it any time you want:
type User = typeof initUser;
const initUser = {name: 'Jon'}
...
const [user, setUser] = useState<User>(initUser);
About I interface prefixes: https://basarat.gitbooks.io/typescript/content/docs/styleguide/styleguide.html#interface
Use this
const [user, setUser] = useState<IUser>({name: 'Jon'});
See the corresponding type here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8a1b68be3a64e5d2aa1070f68cc935d668a976ad/types/react/index.d.ts#L844
https://fettblog.eu/typescript-react/hooks/
// import useState next to FunctionComponent
import React, { FunctionComponent, useState } from 'react';
// our components props accept a number for the initial value
const Counter:FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
// since we pass a number here, clicks is going to be a number.
// setClicks is a function that accepts either a number or a function returning
// a number
const [clicks, setClicks] = useState(initial);
return <>
<p>Clicks: {clicks}</p>
<button onClick={() => setClicks(clicks+1)}>+</button>
<button onClick={() => setClicks(clicks-1)}>-</button>
</>
}
First useState
takes a generic, which will be your IUser. If you then want to pass around the second destructured element that is returned by useState
you will need to import Dispatch. Consider this extended version of your example that has a click handler:
import React, { useState, Dispatch } from 'react';
interface IUser {
name: string;
}
export const yourComponent = (setUser: Dispatch<IUser>) => {
const [user, setUser] = useState<IUser>({name: 'Jon'});
const clickHander = (stateSetter: Dispatch<IUser>) => {
stateSetter({name : 'Jane'});
}
return (
<div>
<button onClick={() => { clickHander(setUser) }}>Change Name</button>
</div>
)
}
See this answer.