Angular EventEmitter with different types

Viewed 60

I’m building a checkbox component that can manage three states depending on if a prop is passed.

@Input() value: boolean|null = false;
@Input() triState = false;

@Output() valueChange = new EventEmitter<boolean|null>();

So when I want to manage a 3-state value it works, I pass in a variable of type boolean|null and no problem.

However, if I just want a normal two-state checkbox, I still have to pass in a variable of boolean|null type, which I find annoying for the client code. Passing a boolean value gives me the following error:

(For the value prop)
Type ‘boolean|null’ is not assignable to type ‘boolean’. Type ‘null’ is not assignable to type ‘boolean’.

I know that this is because my EventEmitter emits boolean|null. So what would be the best way to solve this? Is there a way to emit only a boolean if triState is false, and boolean or null if it’s true?

1 Answers

I see two possible options:

  1. Using types for the EventEmitter generics:

    export type TriState = boolean | null;
    export type DualState = boolean;
    
    @Output() stateChange = new EventEmitter<DualState|TriState>();
    
  2. Creating two separate event emitters:

    @Output() dualStateChange = new EventEmitter<boolean>();
    @Output() triStateChange = new EventEmitter<boolean|null>();
    
    • if triState is true, you would emit from triStateChange, else from dualStateChange.
Related