[英]Typescript: use the same class with different types
定義類和使用的類型的每一個對象的時候我真的很喜歡打字稿的嚴格,但我最近一直面臨着東西,我想是DRY ER:
我有一個類定義,使用和創建特定的對象讓我們說ClientsDB
:
class ClientsDB {
constructor(name: string) {
this.DB = new Database(name);
}
DB: Database;
replaySubject = new ReplaySubject<Client[]>(1);
up() {
fromPromise(this.DB.getDocs<Client>())
.subscribe((clients) => this.replaySubject.next(clients));
}
subscribe(callback: (value: Client[]) => void) {
return this.replaySubject.subscribe(callback);
}
}
問題是我想為ProductsDB
使用相同類型的類,它在純JavaScript中完全相同,但使用不同的類型:
class ProductsDB {
constructor(name: string) {
this.DB = new Database(name);
}
DB: Database;
replaySubject = new ReplaySubject<Product[]>(1);
up() {
fromPromise(this.DB.getDocs<Product>())
.subscribe((products) => this.replaySubject.next(products));
}
subscribe(callback: (value: Product[]) => void) {
return this.replaySubject.subscribe(callback);
}
}
我怎么能只獲得一個類定義,但使用與這些類型定義相同的嚴格性?
您可以使用泛型來實例化不同類型的類。 在運行時,泛型被擦除,您將擁有一個JS類。 由於您還需要創建類的對象,因此您需要將項的構造函數作為參數傳遞給類:
class DBClient<T> {
constructor(name: string, public itemCtor: new (data: any) => T) {
this.DB = new Database(name);
}
DB: Database;
replaySubject = new ReplaySubject<T[]>(1);
up() {
fromPromise(this.DB.getDocs<T>())
.pipe(map(res => res.rows.map(x => new this.itemCtor(x.doc))))
.subscribe((clients) => this.replaySubject.next(clients));
}
subscribe(callback: (value: T[]) => void) {
return this.replaySubject.subscribe(callback);
}
}
let products = new DBClient("", Product)
let clients = new DBClient("", Client)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.