首页 > 解决方案 > Typescript 中的不同类型

问题描述

我正在考虑一个很好的解决方案,当一个函数可以返回两种不同的类型时,如何区分类型。例如,我目前为 Excel 开发一些东西,我从 Office API 获取数据。

根据是“Cell”还是“CellRange”,作为字符串的数据可能会有所不同。

例如,我已经替换了this.checkSomething不会改变问题的实际逻辑。

detectCoordinateOrCell(adress: string): CellRange|Cell {
    if (this.checkSomething(address)) {
      return new CellRange(adress);
    } else {
      return new Cell(adress);
    }
}

从这个方法接收到一些对象后,你通常会如何检查这些类型detectCoordinateOrCell

我尝试实现更简洁的代码和更好的代码设计。我知道可能不只是一个确切的解决方案,但你可能比我知道的更多地了解 Typescript。

标签: javascriptangulartypescripttypes

解决方案


您可以使用地址 instanceof CellRange 地址 instanceof Cell


推荐阅读