什么是 constructor signature in interface
接口中的 constructor signature 不能在類中實現; 它們僅用于定義定義 newable 的現有 JS API. 下面是一個例子:
interface ComesFromString {name: string; }意思是這個接口代表一個可以使用 `new` 操作符操作的對象。返回的類型是 ComesFromStringinterface StringConstructable {new(n: string): ComesFromString; }class MadeFromString implements ComesFromString {constructor (public name: string) {console.log('ctor invoked');} }// 下面函數定義了一個工廠方法。工廠方法的輸入就是之前定義的 constructor signaturefunction makeObj(n: StringConstructable) {return new n('hello!'); }console.log(makeObj(MadeFromString).name);執行結果:
以上例子實際上為 makeObj 的函數調用創建了一個 constraint,傳入的輸入參數必須可以被 new 操作施加,并且構造函數僅包含一個輸入參數,類型為 string.
下列代碼會引起編譯錯誤:
class Other implements ComesFromString {constructor (public name: string, count: number) {} }makeObj(Other);Argument of type ‘typeof Other’ is not assignable to parameter of type ‘StringConstructable’.(2345)
添加問號將其設置為 optional 參數后,問題消失:
具有構造簽名的接口并不意味著由任何類實現(乍一看,這對于一些具有 C#/Java 背景的開發人員來說可能看起來很奇怪,但這確實是另一種不同的設計思路)。
暫時把它想象成一個帶有調用簽名的接口(就像Java世界中的@FunctionalInterface)。 它的目的是描述一種函數類型。所描述的簽名應該由函數對象滿足。但不僅僅是任何高級函數或方法。 它應該是一個知道如何構造對象的函數,一個在使用 new 關鍵字時被調用的函數。
因此,帶有構造簽名的接口定義了構造函數的簽名。如上圖我舉過的例子,makeObj 函數只接受構造函數僅僅包含唯一一個輸入參數且數據類型為 string.
例子:
interface ClassicInterface { // old school interface like in C#/Javamethod1():string;methodN():string; }interface Factory { //knows how to construct an object// NOTE: pay attention to the return typenew (myNumberParam: number, myStringParam: string): ClassicInterface }class MyImplementation implements ClassicInterface {// The constructor looks like the signature described in Factoryconstructor(num: number, s: string) { console.log('in myImplementation:', num, s);} // obviously returns an instance of ClassicInterfacemethod1() {return '1';}methodN() {return '2';} }class MyOtherImplementation implements ClassicInterface {// The constructor looks like the signature described in Factoryconstructor(n: number, s: string) { console.log('in myOtherImplementation:', n, s);} // obviously returns an instance of ClassicInterfacemethod1() {return '3';}methodN() {return '4';} }// And here is the polymorphism of construction function instantiateClassicInterface(ctor: Factory, myNumberParam: number, myStringParam: string): ClassicInterface {return new ctor(myNumberParam, myStringParam); }// And this is how we do it let iWantTheFirstImpl = instantiateClassicInterface(MyImplementation, 3.14, "smile"); let iWantTheSecondImpl = instantiateClassicInterface(MyOtherImplementation, 42, "vafli"); console.log('done');輸出:
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的什么是 constructor signature in interface的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “华为坤灵”子品牌发布:面向分销市场,将
- 下一篇: 滴滴能打到自动驾驶汽车了 UP主体验:车