React&TypeScript-`React.Component`和`typeof React.Component`有什么区别

时间:2018-08-11 09:30:37

标签: reactjs typescript

给出:

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

T1和T2有什么区别?


进一步的问题。给定以下类定义:

class CardHeader extends React.Component {...}

以及将其呈现在其他位置的函数:

功能定义1:

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

功能定义2:

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

定义#1无法正常工作,并且TS(版本2.9.2)在<Comp />处给我以下错误:

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

我很困惑-React.Component是不是一种类型?

对于#2 Comp: typeof React.Component,另一种类型是什么?

1 个答案:

答案 0 :(得分:3)

使用typeof可以获得实例的类型,一个类基本上具有两个方面。静态端(带有构造函数/静态变量和方法),实例端带有非静态内容。

使用typeof(类)时,您引用的是类的静态方面,因此有效的类型仅是类,而不是类的实例。

这里有个例子:

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();
相关问题