打字稿:使用不同类型的同一个类

时间:2018-05-24 08:30:39

标签: javascript typescript types

在定义类和使用的每个对象的类型时,我真的很喜欢Typescript的严格性,但我最近遇到了一些我想要的东西DRY

我有一个类定义,使用和创建特定对象让我们说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);
  }
}

我怎样才能获得一个类定义,但使用与这些类型定义相同的严格性?

1 个答案:

答案 0 :(得分:3)

您可以使用泛型来实例化不同类型的类。在运行时,泛型被擦除,您将拥有一个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)
相关问题