Search code examples
typescriptangularoption-type

Optional Value eventEmitter Angular2


I was wondering (since google is not helping me right now). If it is possible to return an Optional value in an emit. I'm using EventEmitter In my angular project, and I want the value to be optional.

I could just slap a null in that value but it would feel slightly dirty, is there any way to make an optional value or would that require me to write an Abstract optional class?


Solution

  • You can add a ? just like you would do in an interface, for example.

    @Output() thisIsMyOutput = new EventEmitter<{
     this_needs_to_send: number | undefined,
     this_might_send?: boolean
    }>();
    

    Now, you can emit this_might_send (or not) without type errors:

    this.thisIsMyOutput.emit({
     this_needs_to_send: 1234
    });