1

I have such code:

   export class Board implements IBoard {
      choosedPiece = false;
    
      constructor() {
        this.clicked();
      }
   }

and functions like this:

    public pieceOnClick(target: EventTarget): void {
        if (this.choosedPiece) {
          const clickedPiece = this.findPiecePosition((target as HTMLDivElement));
    
          if (clickedPiece.instance !== null) {
            this.choosedPiece = false;
            this.clickedEl(target);
          }
        }
      }
    
    
  clicked(): void {
    this.chessBoard.addEventListener('click', ({target}) => {
      if(!this.clickedEl(target)){
        this.clickPiece(target);
      }
    })
  }

And now I have such an error Argument of type 'EventTarget | null' is not assignable to parameter of type 'EventTarget'. Type 'null' is not assignable to type 'EventTarget'.

How to handle it?

3 Answers 3

4

The error comes because not all event target is of the type HTML Element. Other possible types can be XMLHttpRequest, FileReader, AudioNode, AudioContext, etc.

To fix this error you need to tell TypeScript the type. One way is following.

clicked(): void {
    this.chessBoard.addEventListener("click", (event) => {
        const target = event.target as Element;
        if (!this.clickedEl(target)) {
            // this.clickPiece(target);
        }
    });
}

References:

  1. How to Fix "Property '...' does not exist on type 'EventTarget'" TypeScript Error?
  2. Type 'null' is not assignable to type 'HTMLInputElement' ReactJs
Sign up to request clarification or add additional context in comments.

Comments

1

According to the TypeScript typings for DOM, the Event.target property can be null. Therefore, you can first check if the target exists:

this.chessBoard.addEventListener('click', ({ target }) => {
    if (target && !this.clickedEl(target)) {
        this.clickPiece(target);
    }
});

I do remember it being null (or undefined) once, when adding certain mobile APIs in the mix, but otherwise it's always been defined. But to be sure, a simple check is fine, which also causes TypeScript to accept it due to type narrowing.

Comments

0

I think there are some possibilities to get null instead of EventTarget on the target variable. Just add one condition to eliminate null

this.chessBoard.addEventListener('click', ({target}) => {
  if(target && !this.clickedEl(target)){ // This block will be executed if target is not null
        this.clickPiece(target);
  }
})

1 Comment

thanks, now it works, but i have same error for clickedEl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.