Bru*_*Sun 0 typescript reactjs
鉴于:
type T1 = React.Component;
type T2 = typeof React.Component;
Run Code Online (Sandbox Code Playgroud)
T1和T2有什么区别?
进一步的问题。给出以下类定义:
class CardHeader extends React.Component {...}
Run Code Online (Sandbox Code Playgroud)
还有一个将其渲染到其他地方的函数:
函数定义#1:
function renderCardHeader(Comp: React.Component) {
return <Comp />;
}
Run Code Online (Sandbox Code Playgroud)
函数定义#2:
function renderCardHeader(Comp: typeof React.Component) {
return <Comp />;
}
Run Code Online (Sandbox Code Playgroud)
定义 #1 不起作用,TS(版本 2.9.2)在以下位置给出了以下错误<Comp />:
JSX element type 'Comp' does not have any construct or call signatures.
Run Code Online (Sandbox Code Playgroud)
我很困惑——这不是React.Component一个类型吗?
至于#2,Comp: typeof React.Component什么是另一种类型的类型?
使用 typeof 可以获得实例的类型,类基本上有两个方面。静态端(带有构造函数/静态变量和方法)和带有非静态内容的实例端。
当您使用 typeof (class) 时,您引用的是类的静态部分,因此有效类型只是类,而不是类的实例。
这里有一个例子:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1387 次 |
| 最近记录: |