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

如何创建泛型组件函数,确保泛型类型中可访问指定类型的属性?

泛型组件的类型约束解决方案

原代码的核心问题在于泛型T没有任何类型约束,TypeScript无法确认props.type包含props.displayProp对应的属性,也无法保证该属性的值能被React正常渲染。要实现类型安全的泛型组件,我们需要给泛型添加针对性的约束,确保属性可访问且值的类型符合渲染要求。

实现方案

基础版:约束所有属性可渲染

通过泛型约束,确保传入的T是一个对象,且所有属性的值都属于React可渲染类型(React.ReactNode,涵盖字符串、数字、React元素等),同时让displayProp严格对应T的属性键:

import React from 'react';

// 绑定泛型T的属性键与可渲染值类型
type GenericPropType<T extends Record<string, React.ReactNode>> = {
  type: T;
  displayProp: keyof T;
};

export function GenericComponent<T extends Record<string, React.ReactNode>>(
  props: GenericPropType<T>
) {
  return <div>{props.type[props.displayProp]}</div>;
}

代码说明

  • T extends Record<string, React.ReactNode>:限定T必须是对象类型,且所有属性值都能被React渲染,直接解决值类型的合法性问题。
  • displayProp: keyof T:让displayProp的类型严格匹配T的属性名称,避免传入不存在的属性键。

灵活版:仅约束目标属性

如果不需要T的所有属性都可渲染,只要求displayProp指定的属性值符合要求,可以用更精确的约束:

import React from 'react';

type GenericPropType<T, K extends keyof T> = {
  type: T;
  displayProp: K;
} & {
  // 强制T[K]为可渲染类型
  [key in K]: T[K] extends React.ReactNode ? T[K] : never;
};

export function GenericComponent<T, K extends keyof T>(
  props: GenericPropType<T, K>
) {
  return <div>{props.type[props.displayProp]}</div>;
}

这个版本中,只有displayProp指定的属性需要满足可渲染要求,T的其他属性类型不受限制,适配更多场景。

使用示例

const user = { 
  name: 'Alice', 
  age: 28, 
  avatar: <img src="avatar.jpg" alt="avatar" /> 
};

// 合法:name是可渲染的字符串
<GenericComponent type={user} displayProp="name" />;
// 合法:avatar是React元素
<GenericComponent type={user} displayProp="avatar" />;
// 报错:unknown不是user的属性
// <GenericComponent type={user} displayProp="unknown" />;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:12:47