EventEmitter< undefined>之间有什么区别?和EventEmitter< void> ;? [英] What are the differences between EventEmitter<undefined> and EventEmitter<void>?
问题描述
有时候,我们可能会遇到应该省略泛型变量的情况. 像这样:
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
类型同时接受undefined
和null
-因此,以下代码将有效:
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< undefined>之间有什么区别?和EventEmitter< void> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!