使用TypeScript在useState React Hook上设置类型

我正在迁移一个带有TypeScript的React项目,以使用钩子功能(React v16.7.0-alpha),但我不知道如何设置解构元素的类型。

这里有一个例子:

interface IUser {
name: string;
}
...
const [user, setUser] = useState({name: 'Jon'});

我想强制user变量的类型为IUser。我唯一成功的尝试是分两个阶段进行:输入,然后初始化:

let user: IUser;
let setUser: any;
[user, setUser] = useState({name: 'Jon'});

但我相信有更好的办法。同样,setUser应该初始化为一个函数,该函数接受IUser作为输入,并且不返回任何值。

另外,值得注意的是,使用const [user, setUser] = useState({name: 'Jon'});而不进行任何初始化也可以,但我想利用TypeScript对init强制进行类型检查,特别是如果它依赖于某些道具的话。

谢谢你的帮助。

267602 次浏览

使用这个

const [user, setUser] = useState<IUser>({name: 'Jon'});

参见DefinitelyTyped中的对应类型

首先useState接受一个泛型,它将是你的IUser。如果你想传递useState返回的第二个解构元素,你需要导入Dispatch。考虑你的例子的扩展版本,它有一个点击处理程序:

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>
)
}

请看这个回答

你也可以在之前声明初始状态,然后可以在任何你想要的时候调用它:

type User = typeof initUser;
const initUser = {name: 'Jon'}
...
const [user, setUser] = useState<User>(initUser);

关于I接口前缀:https://basarat.gitbooks.io/typescript/content/docs/styleguide/styleguide.html#interface

< a href = " https://fettblog。Eu /typescript-react/hooks/" rel="nofollow noreferrer">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>
</>
}
class Form {
id: NullNumber = null;
name = '';


startTime: NullString = null;
endTime: NullString = null;


lunchStart: NullString = null;
lunchEnd: NullString = null;


[key: string]: string | NullNumber;
}


export const EditDialog: React.FC = () => {
const [form, setForm] = useState<Form>(new Form());




const inputChange = (e: ChangeEvent<HTMLInputElement>) => {
const element = e.target;
setForm((form: Form) => {
form[element.name] = element.value;
return form;
})
}
return (
<Box pt={3}>
<TextField
required
name="name"
label="Наименование"
defaultValue={form.name}
onChange={inputChange}
fullWidth
/>
</Box>
);
}