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

Styled Component在attrs中设置as时,TypeScript无法推断props的解决办法

解决Styled Components默认as="input"时的TypeScript类型错误

问题核心是:虽然你通过attrs给Input设置了默认as="input",但TypeScript仍会基于Base的div类型进行属性校验,导致使用disabled这类input专属属性时抛出错误。以下是两种实用的TypeScript解决方式:

方法一:显式指定组件泛型

直接给styled组件指定默认元素的类型,让TypeScript识别到默认渲染的是input:

import styled from 'styled-components';

const Base = styled.div``;

// 泛型参数分别指定attrs的类型、默认元素的类型
const Input = styled(Base).attrs<{ as?: React.ElementType }>(({ as = 'input' }) => ({ as }))<HTMLInputElement>``;

这样使用<Input disabled={true} />时,TypeScript会默认按照input元素的属性校验,不会再提示div无disabled属性;同时你依然可以通过as属性指定其他元素,比如<Input as="button" type="button" />,此时类型会自动切换为对应元素的属性。

方法二:自定义Props类型

通过结合React内置的ComponentPropsWithoutRef来定义Input的Props,明确默认属性集:

import styled from 'styled-components';
import type { ComponentPropsWithoutRef, ElementType } from 'react';

const Base = styled.div``;

// 定义Input的Props:默认继承input的属性,同时允许as覆盖元素类型
type InputProps = ComponentPropsWithoutRef<'input'> & {
  as?: ElementType;
};

const Input = styled(Base).attrs<InputProps>(({ as = 'input', ...rest }) => ({
  as,
  ...rest,
}))<InputProps>``;

这种方式更灵活,如果你需要给Input添加自定义属性,可以直接在InputProps中扩展,同时保留as属性的动态切换能力。

效果验证

两种方法都能实现:

  • 无需显式传递as="input",直接使用<Input disabled={true} />无类型错误
  • 指定as为其他元素时,TypeScript会自动校验对应元素的属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 12:12:48