简体   繁体   English

Typescript自定义类型声明出错

[英]Error with Typescript custom type declaration

I have the following type-declaration written for r-dom : 我为r-dom编写了以下类型声明:

/// <reference types="react" />

declare module 'r-dom' {

    interface IRDOMFacade extends React.ReactDOM {
        (component: React.Component<any, any>, properties?: Object, children?: React.ReactElement<any>|Array<React.ReactElement<any>>): React.ReactElement<any>
    }

    var r: IRDOMFacade

    export = r
}

A sample component: 一个示例组件:

import * as React from 'react'
import * as r from 'r-dom'

export default class Application extends React.Component<{},{}> {

  render() {
      return r.h1('Hello World')
  }

}

The above component has no type errors. 上面的组件没有类型错误。 But when I try to use r as a function I get type error: 但是当我尝试使用r作为函数时,我得到类型错误:

r(Application)

error TS2345: Argument of type 'typeof Application' is not assignable to parameter of type 'Component'. 错误TS2345:类型'typeof Application'的参数不能分配给'Component'类型的参数。 Property 'setState' is missing in type 'typeof Application'. 'typeof Application'类型中缺少属性'setState'。

I am curious what is wrong here. 我很好奇这里有什么问题。

This was happening because first argument of r was a class/constructor having signature React.Component<any, any> rather than an instance of React.Component<any, any> . 这是发生因为r的第一个参数是一个类/具有构造签名React.Component<any, any>而不是一个实例React.Component<any, any>

So switching to the following fixes the error: 因此,切换到以下修复错误:

interface IRDOMFacade extends React.ReactDOM {
    (
        component: new (...args: any[]) => React.Component<any, any>, 
        properties?: Object, 
        children?: React.ReactElement<any>|Array<React.ReactElement<any>>
    ): React.ReactElement<any>
}

I will keep this open for few days in case someone has a more idiomatic solution. 如果有人有更惯用的解决方案,我会保持开放几天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM