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

TypeScript中如何根据变量类型渲染不同的React组件?

解决TypeScript中多类型变量的渲染分支判断问题

你遇到的核心问题是TypeScript的类型仅存在于编译阶段,运行时无法直接通过typeof判断自定义类型或JSX元素,必须借助运行时可识别的特征做类型守卫。以下是可直接复用的实现方案:

完整代码实现

import React from 'react';

type Type01 = {
  path: string;
  label: string;
};

type ComponentTestType = {
  button: Type01 | "default" | JSX.Element;
};

export function ComponentTest({ button }: ComponentTestType) {
  // 1. 判断字符串字面量"default"
  if (button === "default") {
    return <button type="button">默认按钮组件</button>;
  }
  // 2. 判断Type01类型:通过运行时结构检查做类型窄化
  else if (typeof button === 'object' && button !== null && 'path' in button && 'label' in button) {
    // TypeScript会自动推断此处button为Type01类型
    return <a href={button.path} className="link-btn">{button.label}</a>;
  }
  // 3. 判断JSX.Element:用React内置方法识别React元素
  else if (React.isValidElement(button)) {
    // 直接渲染传入的自定义JSX元素
    return button;
  }
  // 兜底处理(可选,避免类型穷尽报错)
  return null;
}

关键逻辑说明

  • 字符串字面量"default":直接用全等判断即可,因为这是运行时存在的具体值,无需额外处理。
  • 自定义对象类型Type01:通过检查typeof button === 'object'(同时排除null),再验证对象是否包含path和label属性,TypeScript会基于这些条件自动完成类型窄化,将button推断为Type01。
  • JSX.Element:使用React官方提供的React.isValidElement()方法,这是识别React元素的标准方式,能准确区分自定义组件、原生DOM元素等JSX类型。

如果需要更严谨的类型校验,可封装独立的类型守卫函数:

// 封装Type01类型守卫
function isType01(value: unknown): value is Type01 {
  return (
    typeof value === 'object' &&
    value !== null &&
    'path' in value &&
    typeof (value as Type01).path === 'string' &&
    'label' in value &&
    typeof (value as Type01).label === 'string'
  );
}

// 使用类型守卫简化判断
else if (isType01(button)) {
  // 此处button会被严格推断为Type01类型
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:30:14