使用 React 的 useState 钩子时键入可空状态的正确方法 [英] Correct way to type nullable state when using React's useState hook

查看:29
本文介绍了使用 React 的 useState 钩子时键入可空状态的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何键入 useState 函数,因为它返回一个元组.本质上,我必须提供 null 作为 email 的初始值,即假设我不能在这里使用空字符串.

I am having trouble figuring out how to type useState function since it returns a tuple. In essence, I have to provide null as initial value for email i.e. lets assume I can't use empty string here.

然后我有 setEmail 函数来更新这个状态值,它将电子邮件作为字符串.

I then have setEmail function to update this state value, which takes in email as string.

理想情况下,我想输入我的 useState,因此它希望电子邮件尽可能为字符串或空值.目前它仅将其继承为 null

ideally I would like to type my useState so it expects email to be either string or null if possible. At the moment it inherits it as only null

import * as React from "react";

const { useState } = React;

function Example() {
  const [state, setState] = useState({ email: null, password: null });

  function setEmail(email: string) {
    setState(prevState => ({ ...prevState, email }))
  }

  return <p>{state.email}</p>
}

setEmail 函数返回以下错误,因为函数参数中的 string 不是 useState() 中指定的 null 的有效类型

Following error is returned for setEmail function since string in function argument is not valid type for null specified in useState()

[ts]
Argument of type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to parameter of type 'SetStateAction<{ email: null; password: null; }>'.
  Type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to type '(prevState: { email: null; password: null; }) => { email: null; password: null; }'.
    Type '{ email: string; password: null; }' is not assignable to type '{ email: null; password: null; }'.
      Types of property 'email' are incompatible.
        Type 'string' is not assignable to type 'null'. [2345]
(parameter) prevState: {
    email: null;
    password: null;
}

推荐答案

目前,TypeScript 编译器认为 emailpassword 的类型为 null代码>(没有其他值).您可以通过向 useState 调用提供显式类型参数来解决此问题,以便 emailpassword 的类型已知为 字符串null.

Currently, the TypeScript compiler thinks the type of email and password are null (and no other value). You can resolve this by providing an explicit type parameter to the useState call so that the types of email and password are known to be string or null.

const { useState } = React;

function Example() {
  const [state, setState] = useState<{email: null | string, password: null | string}>({ email: null, password: null });

  function setEmail(email: string) {
    setState(prevState => ({ ...prevState, email }))
  }

  return <p>{state.email}</p>
}

这篇关于使用 React 的 useState 钩子时键入可空状态的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆