Anton  Korneychuk
Anton Korneychuk

Reputation: 722

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
  }
}

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

What is your opinion?

Upvotes: 30

Views: 18991

Answers (1)

Joe Clay
Joe Clay

Reputation: 35797

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);
  }
}

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.

Upvotes: 43

Related Questions