问题描述
我正在迁移 React with TypeScript 项目以使用钩子功能 (React v16.7.0-alpha),但我不知道如何设置解构元素的类型.
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.
这是一个例子:
interface IUser {
name: string;
}
...
const [user, setUser] = useState({name: 'Jon'});
我想强制 user
变量为 IUser
类型.我唯一成功的试验是分两个阶段进行:打字,然后初始化:
I want to force user
variable to be of type IUser
. My only successful trial, is doing it in two phases: Typing, then initializing:
let user: IUser;
let setUser: any;
[user, setUser] = useState({name: 'Jon'});
但我相信有更好的方法.另外,setUser
应该被初始化为一个函数,它接受一个 IUser
作为输入,并且什么都不返回.
But I'm sure there is a better way. Also, setUser
should be initialized as a function that takes a IUser
as input, and returns nothing.
另外,值得注意的是使用 const [user, setUser] = useState({name: 'Jon'});
没有任何初始化工作正常,但我想利用 TypeScript强制对 init 进行类型检查,尤其是当它依赖于某些 props 时.
Also, worth noting that using const [user, setUser] = useState({name: 'Jon'});
without any initialization works fine, but I would like to take advantage of TypeScript to force type checking on init, especially if it depends on some props.
感谢您的帮助.
推荐答案
使用这个
const [user, setUser] = useState<IUser>({name: 'Jon'});
这篇关于使用 TypeScript 在 useState React Hook 上设置类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!