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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53650468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:00:16  来源:igfitidea点击:

Set types on useState React Hook with TypeScript

reactjstypescriptreact-hooks

提问by htaidirt

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.

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

Here is an example:

下面是一个例子:

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

I want to force uservariable to be of type IUser. My only successful trial, is doing it in two phases: Typing, then initializing:

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

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

But I'm sure there is a better way. Also, setUsershould be initialized as a function that takes a IUseras input, and returns nothing.

但我相信有更好的方法。此外,setUser应该初始化为一个将 aIUser作为输入并且不返回任何内容的函数。

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({name: 'Jon'});没有任何初始化的情况下使用效果很好,但我想利用 TypeScript 来强制对 init 进行类型检查,特别是如果它依赖于某些道具。

Thanks for your help.

谢谢你的帮助。

回答by cham

First useStatetakes a generic, which will be your IUser. If you then want to pass around the second destructured element that is returned by useStateyou will need to import Dispatch. Consider this extended version of your example that has a click handler:

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

See this answer.

看到这个答案

回答by hello world printer

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

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