Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 为什么hasOwnProperty方法没有';t消除{}型_Reactjs_Typescript_React Native - Fatal编程技术网

Reactjs 为什么hasOwnProperty方法没有';t消除{}型

Reactjs 为什么hasOwnProperty方法没有';t消除{}型,reactjs,typescript,react-native,Reactjs,Typescript,React Native,我从@types/react 16.9.17版本和TypeScript v3.7.4版本中获得了一个复杂类型ReactNode import React, { ReactNode } from 'react'; 我想把这个类型简化为类型,它有属性子类 我尝试使用隐式类型保护来实现这一点: import React, { ReactNode } from 'react'; function func(x: ReactNode) { if (typeof x === 'object' &am

我从@types/react 16.9.17版本和TypeScript v3.7.4版本中获得了一个复杂类型ReactNode

import React, { ReactNode } from 'react';
我想把这个类型简化为类型,它有属性子类

我尝试使用隐式类型保护来实现这一点:

import React, { ReactNode } from 'react';

function func(x: ReactNode) {
  if (typeof x === 'object' && x !== null && x.hasOwnProperty("children")) {
    x.children
  }
}
但我看到错误类型“{}”上不存在属性“children”

问题:

  • 为什么我看到这个错误(为什么typescript在
    hasOwnProperty()
    检查之后不删除空的
    {}
    类型)

  • 通常如何从
    {}类型
    类型中删除
    {}
    类型

  • 如何将反应节点类型化为类型,并具有子属性属性

  • Object.prototype.hasOwnProperty
    不会通过控制流缩小您的类型(下面的签名):

    为了使其成为一个,您可以为
    hasOwnProperty
    ()添加一个全局签名:


    难道
    x
    不应该是
    组件
    反应组件
    类型吗?
    hasOwnProperty(v: PropertyKey): boolean;
    
    declare global {
      interface Object {
        hasOwnProperty<K extends string>(v: K): this is Record<K, any>;
      }
    }
    
    function func(x: ReactNode) {
        if (typeof x === 'object' && x !== null && x.hasOwnProperty("children")) {
            x.children // x: React.ReactPortal
        }
    }