打字稿返回类型:void [英] Typescript Return Type: void

查看:93
本文介绍了打字稿返回类型:void的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Typescript(在Angular项目中使用)中不返回任何内容(无效)的方法,以下哪种是最佳做法?

In Typescript (using in an Angular project) for a method that returns nothing (void), which of the below is best practice?

onSelect(someNumber: number): void {

}

OR

onSelect(someNumber: number) {

}

我在不同的示例中都看到了这两种方式,并且不确定将返回类型添加为void还是将其保留为空白是否更好?

I've seen it both ways in different examples and wasn't sure if it is better to add the return type as void or leave it blank?

推荐答案

无论您是否显式注释方法的返回类型,尤其是对于像void这样的琐碎类型,都完全是个人喜好.

It's entirely personal preference whether you explicitly annotate a method's return type or not, especially for a trivial type like void.

可能要添加: void的原因:

  • 提高清晰度-其他开发人员无需阅读方法主体即可查看其是否返回任何内容
  • 更安全-例如将代码从另一个函数移到其中具有return expr;语句的那个​​函数中,TypeScript将标记此错误
  • Improves clarity - other devs don't have to read the method body to see if it returns anything
  • Safer - if you e.g. move code from another function into this one that has a return expr; statement in it, TypeScript will flag this mistake

您可能不会这样做的原因:

Reasons you might not:

  • 简洁-如果从上下文中可以清楚知道返回类型应该是什么(例如,getLength()几乎肯定会返回number),那么返回类型注释会有点嘈杂
  • 灵活性-如果您要编写此代码的原型,并且不确定要返回的类型是什么,则将其保留为推断状态可以使您更轻松地进行更改
  • Brevity - if it's clear from context what the return type should be (e.g. getLength() is almost certainly returning number), then a return type annotation is slightly noisy
  • Flexibility - if you're prototyping this code and aren't sure yet what you want the return type to be, leaving it inferred lets you change it more easily

这篇关于打字稿返回类型:void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆