[英]How to use a class type as a typed variable? (Typescript)
假設您有一個接口,然后是實現它的類。
interface A { /*do stuff*/ }
class B implements A { /*do stuff*/ }
class C implements A { /*do stuff*/ }
那么如果你有一個變量可以存儲 class 類型,而不是 object 的特定實例,你把什么作為類型?
let x: Something = B; // or C
我知道你可以使用 typeof 的對象,但你不能使用接口。 但是我能夠指定變量來存儲接口的實現,所以我不明白為什么我不能存儲接口的類。
您可以使用構造函數簽名(類似於 function 簽名,但前面有一個new
):
interface A { /*do stuff*/ }
class B implements A { /*do stuff*/ }
class C implements A { /*do stuff*/ }
let x: new () => A = B;
let x2: new () => A = C;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.