![](/img/trans.png)
[英]How to create a class implementing an interface with a nameless function in Typescript?
[英]How to write a TypeScript function accepting a class implementing an interface as a parameter?
我想編寫一個函數,該函數接受一個類作為參數,但只接受implement
特定接口的類。
我知道我可以使用any
,但是最好依靠類型系統來強制執行此操作。
一些偽代碼來表達我的意思...
interface MyInterface { ... }
class Class1 implements MyInterface { ... }
class Class2 { ... }
function doStuff(classParameter: Class implements MyInterface) { ... }
doStuff(Class1); // OK
doStuff(Class2); // Error
您可以使用構造函數簽名來強制執行以下事實:構造函數將返回與接口兼容的實例。 您可以將其用作通用參數約束,也可以直接用作參數,具體取決於您需要對類進行的操作:
interface MyInterface { foo: number }
class Class1 implements MyInterface { foo: number }
class Class2 { bar: number }
function doStuff0(classParameter: new (...args: any[]) => MyInterface) { }
doStuff0(Class1); // OK
doStuff0(Class2); // Error
function doStuff1<T extends new (...args: any[]) => MyInterface>(classParameter: T) { }
doStuff1(Class1); // OK
doStuff1(Class2); // Error
注意我在示例中添加了成員,不要忘記Typescript使用結構類型系統,因此兼容性是由成員而不是通過implements MyInterface
聲明來確定的,因此,如果MyInterface
為空,則任何類都是兼容的,如果MyInterface
為空,則該類是兼容的有一個foo
成員,即使它沒有顯式聲明implements MyInterface
也許您可以使用泛型來實現您想做的事情。 這是一種解決方法:
function doStuff<T extends myInterface>(classParameter: T) {
...
}
所以在這里,T是一個動態類型,必須實現myInterface(是的,在討論接口時關鍵字擴展在這里很奇怪)。
您可以查看下面的文檔,“通用約束”部分https://www.typescriptlang.org/docs/handbook/generics.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.