【发布时间】:2021-02-16 01:07:55
【问题描述】:
如果我以通常的方式声明一个类,我可以使用类名作为类型:
class Foo {
foo: number
constructor(x: number) {
this.foo = x
}
}
let foo : Foo // all fine
但是如果我通过将类表达式分配给变量来声明一个类,我就不能将该名称用作类型:
const Bar = class Bar {
bar: string
constructor(x: string) {
this.bar = x
}
}
let b: Bar // 'Bar' refers to a value, but is being used as a type here. Did you mean 'typeof Bar'?
按照建议使用typeof Bar 不起作用,因为我想要Bar 的实例类型,而不是类本身的类型。
如何获取第二种方式定义的类的实例类型?
基本原理
我对以这种方式定义类感兴趣的原因是我希望有一个接口来描述某些类将具有的静态方法,如 in the handbook here 所述(该部分中的第三个示例)。
Here's that example with a single line added showing the problem again
【问题讨论】:
标签: typescript