14

Question is same as this:

TypeScript: Property 'checked' does not exist on type 'EventTarget & Element'. Why it doesn't exist?

But only for different framework.

I need this answear for ANGULAR 2+ . Currently i am using angular 9

public CheckBoxChange(event: Event) { 
    this.service.change(this.d!.id.toString(), event.target.checked).subscribe(res => {
        console.log(res
    }, err => {
        console.log(err)
    })
}

Problem is here event.target.checked

Error message:

Property 'checked' does not exist on type 'EventTarget'.ts(2339)

How to fix this ? Ok i can set type: any but this is not solution.

jesox1
  • 173
  • 1
  • 1
  • 6

1 Answers1

20

Event is a rather generic class and so is EventTarget. At the position, you are accessing event.target there is no way for the TS compiler to deduce, that this event.target is indeed a checkbox, so it assumes it to be a generic HTMLElement. If you want to access properties of a checkbox, which is a HTMLInputElement, you have to specify the type yourself.

public CheckBoxChange(event: Event) { 
    const ischecked = (<HTMLInputElement>event.target).checked
    this.service.change(this.d!.id.toString(), ischecked).subscribe(res => {
        console.log(res
    }, err => {
        console.log(err)
    })
}
derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • 1
    Nice solution. Unfortunately now It is giving an error: `'event' is deprecated.ts(6385)`. The more straightforward correction is to, instead of passing the event in the template, pass the target. Then in the handler, you receive `$target: EventTarget` and get the ischecked with `const ischecked = ($target).checked;` – user3658510 Aug 04 '22 at 19:28