【发布时间】:2021-09-04 05:04:02
【问题描述】:
我正在写一个对象接口,其中一个是一个属性值是一个类。但是 ts 编译器会当这个类扩展其他类时抛出异常。
这是一个简单的例子:
class Base {
key: string
}
class Foo extends Base { }
interface Obj {
list: Foo[]
value: Foo
}
const obj: Obj = {
list: [new Foo()],
value: Foo // < Throws error here
}
错误内容:
Property 'key' is missing in type 'typeof Foo' but required in type 'Base'.ts(2741)
test.ts(39, 5): 'key' is declared here.
test.ts(51, 12): Did you mean to use 'new' with this expression?
当我删除 Foo 中的扩展时,错误消失了:
class Foo { } // < delete extends here
interface Obj {
list: Foo[]
value: Foo
}
const obj: Obj = {
list: [new Foo()],
value: Foo // < No error throw
}
据我了解,Foo 是从Base 扩展而来的,因此它应该在Base 中包含相关属性,但编译器告诉我它没有。
那么有什么办法可以解决这个问题吗?
泛型错误
还有一个问题。当我在Obj 上使用泛型时,因为有多种类型扩展Base。像这样:
class Foo extends Base { }
class Bar extends Base { }
interface Obj<T extends Base> {
list: Foo[]
value: typeof T // < Throws error here
}
const obj: Obj<Foo> = {
list: [new Foo()],
value: Foo
}
编译器会抛出如下异常:
'T' only refers to a type, but is being used as a value here.
有没有办法让泛型定义更完整一点?
我使用的版本
- 节点
12.16.1 - 打字稿
3.8.3和4.3.4
【问题讨论】:
标签: javascript typescript class extends