首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TypeScript,检查键和子键及其变体

TypeScript,检查键和子键及其变体
EN

Code Review用户
提问于 2017-04-30 22:28:21
回答 1查看 154关注 0票数 1

如何减少代码大小?

代码语言:javascript
复制
  getAlreadySaved(goal: GoalModel): number {

        if (goal.status && goal.status.investedAmount && !goal.status.pendingIncoming && !goal.status.pendingOutgoing) {
            return goal.status.investedAmount;

        } else if (goal.status && goal.status.investedAmount && goal.status.pendingIncoming && !goal.status.pendingOutgoing) {
            return goal.status.investedAmount + goal.status.pendingIncoming;

        } else if (goal.status && goal.status.investedAmount && !goal.status.pendingIncoming && goal.status.pendingOutgoing) {
            return goal.status.investedAmount - goal.status.pendingOutgoing;

        } else if (goal.status && goal.status.investedAmount && goal.status.pendingIncoming && goal.status.pendingOutgoing) {
            return goal.status.investedAmount + goal.status.pendingIncoming - goal.status.pendingOutgoing;

        } else {
            return 0;
        }

    }
EN

回答 1

Code Review用户

发布于 2017-05-01 00:21:14

先找出无效案例,然后早点返回。在本例中,最初的goal.status检查主要用于存在检查。您可以从整个逻辑中删除它,并将其放在前面,提前返回0

现在,TypeScript的全部目的是为您的数据提供类型,这样您就不会在代码中进行不必要的类型检查。在pendingIncomingpendingOutgoinginvestedAmount的例子中,它们是数字。status的类型至少应该将它们定义为number。如果没有值,它们至少应该初始化为0。这应该消除不必要的条件。

这样,您的代码基本上就是:

代码语言:javascript
复制
getAlreadySaved(goal: GoalModel): number {
  const status:Status = goal.status;

  if(!status) return 0;

  // If we can assume they're numbers, we can safely say we can do math.
  return status.investedAmount + status.pendingIncoming - status.pendingOutgoing;
}
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/162196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档