javascript - 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
?
- 添加一些辅助方法?
- 让任何地方都成为 if/else
- 在课堂上(单元格/单元格范围)?
- 或完全不同的东西
我尝试实现更简洁的代码和更好的代码设计。我知道可能不只是一个确切的解决方案,但你可能比我知道的更多地了解 Typescript。
解决方案
您可以使用地址 instanceof CellRange 地址 instanceof Cell
推荐阅读
- mysql - pandas to sql raise mysql raise errorclass(errno, errval)
- python - 我如何绘制浮动列表
- go - SQLMock - 模拟出链式 DELETE 查询
- c# - 如何在不需要文本框的情况下从我的视图模型中使用条形码阅读器获取条形码的值?wpf c#
- python - 通过以下链接从新站点刮取数据
- oauth-2.0 - 在 OpenID 连接授权代码流中使用 PKCE 时我们需要 client_secret 吗?
- python - Python列表json转换为列表
- excel - 使用 excel 中的拖动功能以逗号分隔和顺序增加单元格中的数字
- c - 权重偏左树中的融合操作
- pandas - pandas - 合并并唯一地重命名具有相同列名的两个数据框的列