有时,我们可以使用泛型变量被省略的情况。如下所示:
@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>.
void更好,因为.emit()调用中没有参数。undefined是更好的.emit()是相同的.emit(undefined)你的意见是什么?
发布于 2017-08-02 15:18:41
根据TypeScript文档,void类型同时接受undefined和null -因此,以下代码将是有效的:
@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或没有参数,这在您的情况下可能更正确--也就是说,我看不到任何重大问题的发生仅仅因为您将null传递给一个发射器,而您并不期望从任何地方得到一个值,所以我会倾向于选择void,因为它是较短的选项。
https://stackoverflow.com/questions/45464495
复制相似问题