简体   繁体   中英

Angular EventEmitter with different types

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM