我无法弄清楚如何键入 useState
函数,因为它返回一个元组。本质上,我必须提供 null
作为 email
的初始值,即假设我不能在这里使用空字符串。
然后我有 setEmail
函数来更新这个状态值,它将电子邮件作为字符串。
理想情况下,我想输入我的 useState
所以如果可能的话,它希望电子邮件为字符串或 null。目前它仅继承它 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>
}
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;
}
原文由 Ilja 发布,翻译遵循 CC BY-SA 4.0 许可协议
目前,TypeScript 编译器认为
email
和password
的类型是null
(没有其他值)。 You can resolve this by providing an explicit type parameter to theuseState
call so that the types ofemail
andpassword
are known to bestring
或null
。