2

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?

1 Answer 1

6

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Very cool! Can you take it one step further and also accept React Stateless components...simply a function like type type Stateless = (props: TextProps) => JSX.Element;? When I tried to union your TextComp type with my Stateless type, React.createElement was complaining at me again :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.