簡體   English   中英

Typescript 子類被接受為超類類型的值,但不作為接受超類類型的 function 的參數

[英]Typescript subclass accepted as value of superclass-type, but not as a parameter of a function that accepts a superclass-type

class Parent {
  str = 'a';
}
class ParentExtended extends Parent {
  num = 1;
}
class MyClass {
  static property?: Parent
  static method (p: Parent): void {}
  static func?: (pParam: Parent) => void
}
const pe: ParentExtended = {
  str: '',
  num: 1
}
// OK
MyClass.property = pe
// OK
MyClass.method(pe)
// Error
MyClass.func = (p: ParentExtended) => {}
Type '(p: ParentExtended) => void' is not assignable to type '(p: Parent) => void'.
  Types of parameters 'p' and 'pParam' are incompatible.
    Property 'num' is missing in type 'Parent' but required in type 'ParentExtended'.ts(2322)

在這里,我的擴展 class 被接受為 static 字段和方法的參數。

但是當我分配MyClass.func (其參數類型是子ParentExtended )一個 function 其參數類型是Parent時,TS 說參數不兼容。 為什么會這樣? 我如何允許它接受接受子 class 的 function (最好沒有泛型)?

提前致謝

您正在嘗試分配 function func聲明為(pParam: Parent) => void一個 function 將被聲明為(p: ParentExtended) => void
由於ParentExtended不是Parent的超級 class ,因此它不起作用。
您不能確保每個繼承Parent行為的 object 也繼承ParentExtended class。
簡單的例子:

class A {}
class B extends A {}
class C extends A {}

function test(obj: A) {}

在 function test中,您可以通過B類型的對象C

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM