具有“解耦”类的多态和类型安全

时间:2019-09-12 13:48:07

标签: typescript generics interface polymorphism instanceof

在我的代码中,我具有用于不同照片集类型的某些类型的类,并且每个类都带有管理该类的服务类(由于整个应用程序的体系结构,我必须坚持这样做)。

这是简化版本中的代码:

interface ICollection {}

class ImportedCollection implements ICollection {}
class CustomCollection implements ICollection {}

class ImportedCollectionsService {
  findPhotos(collection: ImportedCollection) {
    console.log('ImportedCollectionsService.findPhotos');
  }
}
class CustomCollectionsService {
  findPhotos(collection: CustomCollection) {
    console.log('CustomCollectionsService.findPhotos');
  }
}

////////////////////////////////////////////////////////

const importedCollectionsService = new ImportedCollectionsService();
const customCollectionsService = new CustomCollectionsService();

const collection: ICollection = new ImportedCollection();

////////////////////////////////////////////////////////

if (collection instanceof ImportedCollection) {
  importedCollectionsService.findPhotos(collection);
} else if (collection instanceof CustomCollection) {
  customCollectionsService.findPhotos(collection);
}

Stackblitz:https://stackblitz.com/edit/typescript-ydp7xn?file=index.ts

它可以正常工作并且从理论上讲是类型安全的,但是我对代码段末尾的instanceof不满意。相反,我想采用一种面向多态性的方法,以提供更大的灵活性(即,将同一集合类型的所有代码都放在同一位置)。

理想情况下,我会完全摆脱instanceof的检查,但是我不知道那是否有可能。或者,可以使用至少封装支票的解决方案。

我尝试了一下,并获得以下代码:https://stackblitz.com/edit/typescript-vo5yb1 通过使用(通用)接口,我可以强制所有服务类使用特定于集合的参数来实现findPhotos方法,但是我在第40行中丢失了类型安全性(collection被强制转换为{{ 1}})。

如果我让any接受类型为findPhotos的参数,我将把类型安全性问题移到ICollection方法中(该方法需要进行类型声明我需要方法中更专业的集合类型。

是否具有TypeScript功能或更好的体系结构,可以让我解决这些问题,还是最好还是坚持使用原始版本?

最诚挚的问候

0 个答案:

没有答案