Reputation: 24610
When I use React with TypeScript, I usually create a ES6 class to define a component like so:
import * as React from 'react';
interface TextProps { text: string; }
export class Panel extends React.Component<TextProps, any> {
constructor(props: TextProps) {
super(props);
}
render() {
return <div className="panel">{this.props.text}</div>;
}
}
export class Label extends React.Component<TextProps, any> {
constructor(props: TextProps) {
super(props);
}
render() {
return <span className="label">{this.props.text}</span>;
}
}
What I would like to do is create a type that would accept both a Panel
or a Label
.
I tried the following:
type TextComp = React.Component<TextProps, any>;
function create(component: TextComp, text: string) {
return React.createElement(component, { text: text });
}
This shows compiler errors on the React.createElement(component,
parameter but the code runs properly.
How can I define the type TextComp
such that this code compiles without errors using TypeScript version 2.2.1?
Upvotes: 2
Views: 11893
Reputation: 220944
What you want is this:
type TextComp = new(...args: any[]) => React.Component<TextProps, any>;
function create(component: TextComp, text: string) {
return React.createElement(component, { text: text });
}
The root cause is the same as explained at What does the error "JSX element type '...' does not have any construct or call signatures" mean?
Upvotes: 6