EventEmitter< undefined>之间有什么区别?和EventEmitter< void&gt ;? [英] What are the differences between EventEmitter<undefined> and EventEmitter<void>?

查看:101
本文介绍了EventEmitter< undefined>之间有什么区别?和EventEmitter< void&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我们可能会遇到应该省略泛型变量的情况. 像这样:

Some times we can have a case when generic variable should be omitted. Like this:

@Component( ... )
class MyComponent {

  @Output()
  public cancel = new EventEmitter<undefined>();

  private myFoo() {
    this.cancel.emit(); // no need to pass any value
  }
}

因此,问题:哪种是定义EventEmitter类型的更好方法:
EventEmitter<undefined>EventEmitter<void>.

So, the question: Which is better way to define the EventEmitter type:
EventEmitter<undefined> or EventEmitter<void>.

  • void更好,因为在.emit()调用中没有参数.
  • undefined更好.emit()是相同的.emit(undefined)
  • void is better because there is no an argument in .emit() call.
  • undefined is better .emit() is the same .emit(undefined)

您对此有何看法?

推荐答案

根据TypeScript文档,void类型同时接受undefinednull-因此,以下代码将有效:

According to the TypeScript docs, the void type accepts both undefined and null - therefore, the following code would be valid:

@Component( ... )
class MyComponent {

  @Output()
  public cancel = new EventEmitter<void>();

  private myFoo() {
    this.cancel.emit();
    this.cancel.emit(undefined);
    this.cancel.emit(null);
  }
}

使用EventEmitter<undefined>时,您只能传递undefined或不传递任何参数,这在您的情况下可能更正确-也就是说,我看不到仅由于您传递了到您都不希望有任何值的发射器,因此我很想选择void,因为它是较短的选项.

Whereas with EventEmitter<undefined>, you would only be able to pass undefined or no argument, which is probably more correct in your case - that said, I can't see any major issues occurring just because you passed null to an emitter that you're not expecting a value from anyway, so I'd be tempted to choose void since it's the shorter option.

这篇关于EventEmitter&lt; undefined&gt;之间有什么区别?和EventEmitter&lt; void&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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