我被困在Typescript 编译不断失败的部分.

以下是代码:

    (currentCellData.ellipsis && currentCellData.renderValue.props.children ? (
            <NTooltip key={index} title={currentCellData.renderValue} arrow placement="top-start">
              {renderTableCell}
            </NTooltip>
          ) : (
            <Fragment key={index}>{renderTableCell}</Fragment>
          ))

这是renderValue的数据和类型.

enter image description here

declare type TValue = {
    renderValue: string | React.ReactElement;
    onClick?: (e: React.MouseEvent<HTMLTableCellElement>) => void;
    ellipsis?: boolean;
};

我想在renderValue内的props个属性中得到children的值.

然而,当我激活打字脚本编译时,它失败并给出消息

src/components/NTableBody/index.tsx:110:68 - error TS2339: Property 'props' does not exist on type 'string | ReactElement<any, string | JSXElementConstructor<any>>'.
  Property 'props' does not exist on type 'string'.

我认为问题出在renderValue类型的字符串定义上.但是,其他组件也需要字符串定义.

如何解决或绕过此类型问题?

推荐答案

RenderValue的联合类型似乎是string | React.ReactElement,在实际使用之前,基本上需要缩小类型的范围,显然,在这种情况下,在使用其属性之前,您需要判断renderValue是否为React.ReactElement.

建议使用typeof关键字来简单地判断它是否不是字符串,那么它就是ReactElement,如下所示:

const {renderValue} = currentCellData;
typeof renderValue !== 'string' && renderValue.props.children

Typescript相关问答推荐

具有映射返回类型的通用设置实用程序

界面中这种类型的界面界面中的多态性

防止获取发出不需要的请求

需要使用相同组件重新加载路由变更数据—React TSX

在TypeScript中使用泛型的灵活返回值类型

从typescript中的对象数组中获取对象的值作为类型'

具有泛型类方法的类方法修饰符

在映射类型中用作索引时,TypeScrip泛型类型参数无法正常工作

如何以Angular 形式显示验证错误消息

TypeScrip界面属性依赖于以前的属性-针对多种可能情况的简明解决方案

为什么在回调函数的参数中不使用类型保护?

为什么不能使用$EVENT接收字符串数组?

一个打字类型可以实现一个接口吗?

找不到财产的标准方式?

为什么Typescript只在调用方提供显式泛型类型参数时推断此函数的返回类型?

如何在本地存储中声明该类型?

任何导航器都未处理有效负载为";params";:{";roomId";:";...";}}的导航操作

递归类型别名的Typescript 使用

TypeScript:方法获胜';t接受较窄类型作为参数

TS 排除带点符号的键