为什么
func(x2)
有效?当 x2.index
需要 F2
传入但 func
只传递 F1
时
class F1 {
value: string = ''
}
class F2 extends F1 {
value2: number = 0
}
abstract class X1 {
abstract index(param: F1): void
}
class X2 extends X1 {
override index(param: F2): void {
// Here [param] must be [F2]
console.log(`Is F2: ${param instanceof F2}`)
}
}
const func = (x: X1) => {
const f1 = new F1()
x.index(f1)
}
const x2 = new X2()
// Why [X2] can be passed here? No error?
// [X2.index] [param] should only accept [F2]
// But [func] will pass [F1] into it.
func(x2)
// The expected is that [func] should not be able to accept [X2].
func(x2) // Error expected
变量
x2
的类型是X2
,它扩展了X1
。当您调用 func
时,类型将更改为 X1
。对于类型 X1
,唯一已知的索引方法是接受 F1
参数的方法,因此它是有效的,即使继承类“更改”了类型类型。正是由于这个原因,更改重写方法的类型通常被认为是一种不好的做法。
为了获得所需的类型安全性,您需要添加泛型。
如果您将
X1
设为通用,您可以将其限制为每个扩展类的特定类型。一个例子如下:
abstract class X1<TIndex extends F1> {
abstract index(param: TIndex);
}
class X2 extends X1<F2> {
override index(param: F2): void {
}
}
这样,如果您创建
X2
的实例并向索引方法提供 F2
后的任何其他值,您将收到错误。