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

React与TypeScript中data-testid的类型说明及组件props中dataTestId的类型定义方案

在React + TypeScript中为data-testid设置正确的类型

嘿,这个问题其实很好解决,咱们直接说关键点:

dataTestId的类型应该是**string | undefined**(因为你把它设为了可选属性,TypeScript会自动为可选属性加上undefined,所以你只需要写dataTestId?: string就够了)。

为什么是string?

data-testid是我们给HTML元素加的自定义测试标识,几乎所有场景下它的值都是字符串(比如"someid"),这也是测试框架(像React Testing Library)期望的格式,所以string是最贴合实际需求的类型,完全没必要用any。

修正你的代码示例

另外注意你原来的ChildComponentProps语法有小问题,需要用&来合并自定义属性和Pick出来的React输入属性,完整修正后的代码如下:

import { FC } from 'react';

// 正确的Props类型定义
export type ChildComponentProps = {
  dataTestId?: string; // 替换any为string,可选属性自动支持undefined
} & Pick<React.InputHTMLAttributes<HTMLInputElement>, 'id' | 'checked' | 'name'>;

const ChildComponent: FC<ChildComponentProps> = ({ dataTestId, ...props }) => (
  <Switch {...props}>
    <input type="checkbox" data-testid={dataTestId} />
  </Switch>
);

// 使用组件的示例
<ChildComponent dataTestId="someid" id="toggle-switch" checked={false} name="theme-toggle" />

额外小提示

如果你想让类型更严谨,也可以用NonNullable<string>来强制要求传入dataTestId(去掉?),但通常测试ID是可选的,所以保持dataTestId?: string更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 01:47:45