我是Typescript的新手,所以请原谅这个微不足道的问题,但是我试图编写一个接受无状态函数组件(SFC)或类组件的函数。我认为这可能是通过联合类型实现的。但是我收到了错误。
const render = (Component: React.StatelessComponent<any> | React.ComponentClass<any>) => {
// ...
}
错误:
error TS2345: Argument of type 'StatelessComponent<{}> | ComponentClass<{}>' is not assignable to parameter of type 'ComponentClass<{}>'.
Type 'StatelessComponent<{}>' is not assignable to type 'ComponentClass<{}>'.
Type 'StatelessComponent<{}>' provides no match for the signature 'new (props?: {} | undefined, context?: any): Component<{}, ComponentState>'.
我无法弄清楚此错误消息的实际含义。任何帮助将不胜感激。
编辑:
下面的实际代码,我试图将其剥离为例:
index.ts
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { default as Root, Props as RootProps } from './components/Root'
const rootContainer = document.getElementById('root') as HTMLElement
const render = (Component: React.StatelessComponent<any> | React.ComponentClass<any>) => {
const props: RootProps = { message: 'Universe' }
const rootElement: JSX.Element = React.createElement(Component, props)
const wrapperElement: JSX.Element = React.createElement(AppContainer, undefined, rootElement)
ReactDOM.render(wrapperElement, rootContainer)
}
render(Root)
if (module && 'hot' in module) {
module.hot.accept('./components/Root', () => { render(Root) })
}
Root.tsx
import React from 'react'
export interface Props extends React.Props<any> {
message?: string
}
const Root: React.SFC<Props> = (props) => (
<div>Hello { props.message }.</div>
)
Root.defaultProps = {
message: 'world'
}
export default Root