我試圖爲第三方庫創建一個定義文件(*.d.ts
)。這個庫有一個基類,用戶對象最終將繼承它。但是,庫處理這些對象的構造,並將它們自己的內置方法與用戶定義的方法合併。因此,我不能只創建一個用戶類implements
的interface
,因爲用戶類未定義基類的內置方法。TypeScript類接口定義
打字稿定義d.ts
文件:
module otherlib {
export interface Base {
third_party_base_method(): string;
}
}
用戶源:
// FAILS because MyClass doesn't define third_party_base_method()
class MyClass implements otherlib.Base {
myfunc() {
let str = this.third_party_base_method();
}
}
一種解決方法我現在有是創建一個打字稿文件(*.ts
),其限定了class
而不是一個interface
與所有基體類型中具有空體或返回虛擬值的方法。用戶類然後可以從extend
這樣的類型檢查工作。但是,這看起來很不方便,導致不必要的和潛在危險的原型操作。有沒有更好的辦法?
打字稿.ts
文件來定義第三方庫的基類:
module otherlib {
export class Base {
// Dummy stub definition that is never called
third_party_base_method(): string { return "dummy"; }
}
}
用戶來源:
class MyClass extends otherlib.Base {
myfunc() {
// Proper type checking for calling the method that the
// third party library adds to the object.
let str = this.third_party_base_method();
}
}
UPDATE:
我其實開始碰到一些與空的存根函數一起擴展的麻煩。所以,我的新的解決方法就是建立一個存根,使鑄件容易...
打字稿d.ts
文件來定義第三方庫的基類:
module otherlib {
export interface Base {
third_party_base_method(): string;
}
}
打字稿.ts
文件鑄造存根:
module otherlib_stub {
export class Base {
get base(): otherlib.Base { return <otherlib.Base><any>this; }
}
}
用戶來源:
class MyClass extends otherlib_stub.Base implements otherlib.Base {
myfunc() {
// Proper type checking for calling the method that the
// third party library adds to the object.
let str = this.base.third_party_base_method();
}
}
對於那些好奇的人,我正在處理的特定圖書館是Google的Polymer 0.9 – drarmstr
您是否知道Definitely Typed? https://github.com/borisyankov/DefinitelyTyped/tree/master/polymer – Fenton
聚合物在那裏的選項沒有被移植到0.9。另外,它並沒有真正提供創建一個適當的TypeScript類來傳遞給用戶方法中用於處理此上下文的鍵入。 – drarmstr