React中如何为useState变量添加TypeScript类型?解决类型不匹配报错
问题解决:类型不匹配错误的修复
错误原因
你遇到的类型不匹配问题,核心是**useState声明的状态变量类型和实际要比较的类型不一致**:
name是IName类型的对象(结构为{ name: string }),但user.author_name是纯字符串类型password同理,是IPassword类型的对象,和user.password的字符串类型无法直接比较
两种修复方案
方案1:简化状态类型(推荐)
如果你的状态只是单独的字符串,没必要用单独的接口包裹,直接把状态类型声明为 string 即可:
import { FC, useState, FormEvent } from 'react'; interface Props { authors: { author_name: string; password: string; }[]; } const Login: FC<Props> = ({ authors }) => { // 直接声明为string类型的状态 const [name, setName] = useState<string>(""); const [password, setPassword] = useState<string>(""); // 给event添加正确的类型:React.FormEvent const handleSubmit = (event: FormEvent) => { event.preventDefault(); const userData = authors.find( (user) => user.author_name === name && user.password === password ); }; // 组件必须返回合法JSX,补充返回部分 return <form onSubmit={handleSubmit}> {/* 表单输入框等内容 */} <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button type="submit">登录</button> </form>; };
方案2:保留接口,使用对象属性比较
如果一定要保留 IName 和 IPassword 接口(比如后续要扩展状态结构),那么比较时要取对象内部的属性值:
import { FC, useState, FormEvent } from 'react'; interface IName { name: string; } interface IPassword { password: string; } type Props = { authors: { author_name: string; password: string; }[]; }; const Login: FC<Props> = ({ authors }) => { const [name, setName] = useState<IName>({ name: "" }); const [password, setPassword] = useState<IPassword>({ password: "" }); const handleSubmit = (event: FormEvent) => { event.preventDefault(); const userData = authors.find( // 取对象的name和password属性进行比较 (user) => user.author_name === name.name && user.password === password.password ); }; return <form onSubmit={handleSubmit}> <input type="text" value={name.name} onChange={(e) => setName({ name: e.target.value })} /> <input type="password" value={password.password} onChange={(e) => setPassword({ password: e.target.value })} /> <button type="submit">登录</button> </form>; };
额外提示
- 不要忘记给
handleSubmit的event参数添加FormEvent类型,避免隐式any类型警告 - React组件必须返回合法的JSX结构,原代码缺少返回部分,记得补充
内容的提问来源于stack exchange,提问作者user21728832
相关产品推荐
相关产品推荐

