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

自定义Input组件触发TypeScript错误ts(2700),求解决方案

解决TypeScript错误:Rest types may only be created from object types (ts(2700))

错误原因

你在自定义Input组件时使用了React.FC定义组件类型,但FC会自动为props添加children?: ReactNode属性。而<input>是无children的原生元素,InputHTMLAttributes<HTMLInputElement>并不包含children字段,这导致InputProps交叉类型后,解构剩余属性...inputProps时,TypeScript无法将其识别为纯对象类型,从而抛出错误。

对比Button组件能正常运行的原因:<button>元素支持children,ButtonHTMLAttributes<HTMLButtonElement>本身兼容FC的children属性,因此不会出现类型冲突。

解决方案

去掉React.FC的使用,直接给组件函数的参数指定InputProps类型即可:

修改后的Input组件代码

import React, { InputHTMLAttributes } from 'react';

export type InputProps = {
    color: 'default' | 'primary' | 'red' | 'dark';
    size: 'xs' | 'sm' | 'md' | 'lg';
    fullWidth?: boolean;
} & InputHTMLAttributes<HTMLInputElement>;

const Input = ({ color, size, fullWidth, ...inputProps }: InputProps) => {
    return (
        <input {...inputProps} />
    );
};

export default Input;

补充说明

React.FC更适合用于需要渲染children的组件,对于<input>、<img>这类无children的原生元素,直接定义函数参数类型可以避免不必要的类型冲突,让代码更简洁准确。

内容的提问来源于stack exchange,提问作者dokgu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:17:41