首页 文章

TypeScript:JSX元素类型没有任何构造或调用签名

提问于
浏览
1

我正在使用React 16.2.0,TypeScript 2.7.1,并且不允许任何类型 .

主要组成部分:

// index.js

import * as React from 'react'
import Page from './page'
import i18n from '../i18n'

import PageContent from '../components/pageContent'
import withMoreInfo from '../hoc/withMoreInfo'

class Home extends React.Component {
  render () {
    return <Page title={ i18n.t('home.title') }>
      <PageContent />
    </Page>
  }
}

export default withMoreInfo(Home)

特别文件:

import * as React from 'react'

export default function withMoreInfo<T> (Wrapped: T) {
  return class WithMoreInfo extends React.Component<{ asPath: string }> {
    static async getInitialProps ({ asPath }: { asPath: string }) {
      return { asPath }
    }

    render () {
      const { asPath } = this.props
      const language = asPath.indexOf('/ro') === 0 ? 'ro' : 'en'
      return <Wrapped language={ language } pathname={ asPath } />
    }
  }
}

我无法解决此错误: error #TS2604: JSX element type 'Wrapped' does not have any construct or call signatures.

enter image description here

非常感谢任何提示 . 谢谢,保罗

1 回答

  • 2

    您需要告诉编译器该参数是一个构造函数,并返回一个具有属性 languagepathname 的React组件

    function withMoreInfo<T extends React.Component<{ language: string, pathname: string }, any>>(Wrapped: new (props: { language: string, pathname: string }, context?: any) => T) {
        return class WithMoreInfo extends React.Component<{ asPath: string }> {
            static async getInitialProps({ asPath }: { asPath: string }) {
                return { asPath }
            }
    
            render() {
                const { asPath } = this.props
                const language = asPath.indexOf('/ro') === 0 ? 'ro' : 'en'
                return <Wrapped language={language} pathname={asPath} />
            }
        }
    }
    // The component must have properties language and pathname and only those
    class Home extends React.Component<{ language: string, pathname: string }> {
        render() {
            return <div />
        }
    }
    
    export default withMoreInfo(Home)
    

    在您调用 withMoreInfo(Home) 的原始版本中, T 确实是一个反应组件,但是你可以调用 withMoreInfo(1) ,因为 T 绝不受约束 . 对于传递给它的任何类型,泛型函数必须是正确的,因此编译器认为 T 可能是任何东西,所以它可以可靠地对它一无所知 . 解决方案是让编译器知道 Wrapped 参数是反应组件的构造函数,即具有 { language: string, pathname: string } 属性的任何反应组件 T . 构造函数具有与常规函数类似的签名声明,只有 new 关键字,因此 new (props: { language: string, pathname: string }, context?: any) => T

相关问题