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

Viewed 6197

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.

1 Answers

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