首页 > 解决方案 > 反应打字稿和孩子

问题描述

我尝试在打字稿中动态检查反应子组件的类型。以下代码运行良好,但似乎打字稿不希望我解构孩子。

我收到打字稿错误:

TS2339: Property 'type' does not exist on type 'ReactNode'.

我该怎么做才能摆脱打字稿错误而不是使用//@ts-ignore。

import * as React from 'react';

    export interface AuxProps  { 
      children: React.ReactNode[]
    }

    export const Message: React.FC<AuxProps> = ({
      children,
    }: AuxProps) => {
      
      const test = children.filter(({ type }) => type === Test);

      return (
        <div>
          {test}
        <div/>
      );
    };

标签: reactjstypescriptchildren

解决方案


你不能从 中读取typeReactChild因为ReactChild是一个联合,并且不是该联合的每个成员都有一个名为 的属性type

事实上,只有ReactElements 可以。

解决方案是检查谓词函数中的两件事:

  • 这个孩子是ReactElement
  • 如果是,那么该元素是所需类型的吗?

代码:

const test = children.filter(child => React.isValidElement(child) && child.type === 'Test');

推荐阅读