You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 12:47:47