You need to enable JavaScript to run this app. 如何用Typescript实现属性类型随指定属性动态变化的React泛型组件
优惠活动
大模型
产品
解决方案
定价
更多

如何用Typescript实现属性类型随指定属性动态变化的React泛型组件

实现方案

这个需求可以通过TypeScript的可辨识联合类型非常简洁地实现,核心思路是把单选、多选两种模式的属性定义为两个带辨识标识的独立类型,再合并为联合类型作为组件的最终Props,TypeScript会自动根据multiple属性的值推导对应模式下的其他属性类型。

第一步:定义组件属性类型

import React from 'react';

// 提取单选、多选通用的基础属性
type SelectBaseProps<T> = {
  options: T[];
  name: string;
  // 其他通用属性如disabled、placeholder等都可以放在这里
}

// 单选模式专属属性,multiple为false或不传时命中该类型
type SingleSelectProps<T> = SelectBaseProps<T> & {
  multiple?: false;
  value: T;
  renderValues: (selected: T) => JSX.Element;
}

// 多选模式专属属性,multiple为true时命中该类型
type MultiSelectProps<T> = SelectBaseProps<T> & {
  multiple: true;
  value: T[];
  renderValues: (selected: T[]) => JSX.Element;
}

// 组件最终Props为两种模式的联合类型
type SelectProps<T> = SingleSelectProps<T> | MultiSelectProps<T>;

第二步:组件实现

在组件内部只要判断multiple属性的值,TypeScript就会自动收窄当前的Props类型,不需要额外的类型断言:

function SingleOrMultiSelect<T>(props: SelectProps<T>) {
  if (props.multiple) {
    // 此处TS自动识别为多选模式:props.value为T[]类型,renderValues入参自动匹配T[]
    return <div className="select-wrapper">{props.renderValues(props.value)}</div>
  }
  // 此处TS自动识别为单选模式:props.value为T类型,renderValues入参自动匹配T
  return <div className="select-wrapper">{props.renderValues(props.value)}</div>
}

第三步:使用验证

使用时TypeScript会自动根据multiple的值校验其他属性的类型,不需要手动声明泛型:

// 多选模式使用示例
<SingleOrMultiSelect
  multiple={true}
  value={['foo','bar']}
  options={['foo','bar','biz','baz']}
  renderValues={(opts) => <span>{opts.join(', ')}</span>}
  name="示例多选组件"
/>

// 单选模式使用示例(multiple可以省略,默认走单选逻辑)
<SingleOrMultiSelect
  value="foo"
  options={['foo','bar','biz','baz']}
  renderValues={(opt) => <span>当前选中:{opt}</span>}
  name="示例单选组件"
/>

如果需要支持未选中的空状态,只需要给对应模式的value加undefined类型即可,比如单选模式的value定义为T | undefined,多选模式的value定义为T[] | undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 22:54:07