Reactjs 为什么hasOwnProperty方法没有';t消除{}型
我从@types/react 16.9.17版本和TypeScript v3.7.4版本中获得了一个复杂类型ReactNodeReactjs 为什么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
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”
问题:
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
}
}