Reactjs 仅向ComponentClass添加引用的类型脚本

Reactjs 仅向ComponentClass添加引用的类型脚本,reactjs,typescript,Reactjs,Typescript,我有以下意见: function isComponentClass(Component: React.ComponentClass) { return Component.prototype.render; } export const withShortcuts = function<T>(createShortcuts: CreateShortcuts) { return (Component: React.ComponentClass<T> | React

我有以下意见:

function isComponentClass(Component: React.ComponentClass) {
  return Component.prototype.render;
}

export const withShortcuts = function<T>(createShortcuts: CreateShortcuts) {
  return (Component: React.ComponentClass<T> | React.StatelessComponent<T>) => {
    class WrappedShortcuts extends React.Component<T> {
      ref: React.RefObject<T>;
      constructor(props: T) {
        super(props);

        this.ref = React.createRef();
      }

      render() {
        return (
          <Shortcuts createShortcuts={createShortcuts}>
            {isComponentClass(Component) ? <Component ref={this.ref} {...this.props} /> : <Component {...this.props} />}
          </Shortcuts>
        );
      }
    }

    return hoistStatics(WrappedShortcuts, Component);
  };
};
函数isComponentClass(组件:React.ComponentClass){
返回Component.prototype.render;
}
export const with shortcuts=函数(createShortcuts:createShortcuts){
返回(组件:React.ComponentClass | React.statelementComponent)=>{
类WrappedShortcuts扩展React.Component{
ref:React.reObject;
建造师(道具:T){
超级(道具);
this.ref=React.createRef();
}
render(){
返回(
{isComponentClass(组件)?:}
);
}
}
返回起重机静力学(包装短切、部件);
};
};
问题是
isComponentClass
没有让TS编译器知道我可以在类中添加
ref
,如果该值为true,我会得到错误:

属性“ref”不存在于类型“IntrinsicattAttributes&{ 子节点?:ReactNode;}


您需要将
isComponentClass
更改为类型保护。类型保护函数是在if或
?:
中使用时更改传递给它的参数类型的函数。有关类型保护的详细信息,请参见:

函数isComponentClass(组件:React.ComponentClass | React.statelementComponent):组件是React.ComponentClass{
返回Component.prototype.render;
}
isComponentClass(组件)?
://此处的组件是React.ComponentClass
//组件在这里是React.StatelessComponent

听起来不错,但是无状态组件现在在callin
isComponentClass
之后是类型
never
,并抱怨JSX元素类型“component”没有任何构造或调用签名。@dagda1您使用的是什么版本,只是出于好奇,类型保护在该语言中非常古老。我使用的是2.6.2
function isComponentClass<T>(Component: React.ComponentClass<T> | React.StatelessComponent<T>) : Component is React.ComponentClass<T> {
    return Component.prototype.render;
}

isComponentClass(Component) ? 
   <Component ref={this.ref} {...this.props} /> :  // Component is React.ComponentClass<T> here 
   <Component {...this.props} /> // Component is React.StatelessComponent<T> here