0

Given:

type T1 = React.Component;
type T2 = typeof React.Component;

What's the difference between T1 and T2?


Further question. Given the following class definition:

class CardHeader extends React.Component {...}

And a function to render it somewhere else:

Function definition #1:

function renderCardHeader(Comp: React.Component) {
    return <Comp />;
}

Function definition #2:

function renderCardHeader(Comp: typeof React.Component) {
    return <Comp />;
}

Definition #1 is not working and TS (version 2.9.2) is giving me the following error at <Comp />:

JSX element type 'Comp' does not have any construct or call signatures.

I'm very confused - isn't React.Component a type?

And as for #2, Comp: typeof React.Component, what is a type of another type?

1 Answer 1

5

With typeof you get the type of an instance, a class has basically two sides. A static side (with constructor/static variables and methods) and an instance side with non static stuff.

When you use typeof (class) you refer to the static side of the class therefore the valid type is only the class and not an instance of the class.

Here an example:

class Foo {
    static staticMethod() { }
    instanceMethod() {}
}

class Bar extends Foo {}

// instance side
const fooInstance2: Foo = new Bar();
const fooInstance: Foo = new Foo();
fooInstance.instanceMethod();

// static side
const fooClass2: typeof Foo = Bar;
const fooClass: typeof Foo = Foo;
fooClass.staticMethod();

// Errors because static and instance side differ
const fooClass3: typeof Foo = new Foo();
Sign up to request clarification or add additional context in comments.

Comments

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.