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

如何在TypeScript中收窄JSX.Element类型?类型判断报错求解

解决TypeScript判断JSX.Element类型报错的问题

问题出在typeof icon === "JSX.Element"这个判断上——typeof是JavaScript运行时的操作符,它只能返回原生类型的标识(比如"string"、"object"、"function"等),而JSX.Element是TypeScript的静态类型,并非运行时存在的类型。所以这个判断永远会返回false,TypeScript就会提示你该条件无效。

以下是两种可行的解决方法:

方案1:反向判断字符串类型

因为你的变量只有string和JSX.Element两种可能,直接判断是否为字符串即可,逻辑简单且符合运行时规则:

function MyComponent(): JSX.Element {
  let icon: JSX.Element | string = "/example.png";

  return <div>{typeof icon === "string" ? <img src={icon} /> : icon}</div>;
}

方案2:用React的isValidElement精准判断

如果需要更严谨地识别React元素(比如避免把普通对象误判为元素),可以使用React内置的isValidElement函数,它能在运行时准确判断一个值是否是React元素:

import React from 'react';

function MyComponent(): JSX.Element {
  let icon: JSX.Element | string = "/example.png";

  return <div>{React.isValidElement(icon) ? icon : <img src={icon} />}</div>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:05:27