Derby
Derby

Reputation: 23

TypeScript problems with functions

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?

Upvotes: 1

Views: 79

Answers (3)

Darshna Rekha
Darshna Rekha

Reputation: 1116

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

Upvotes: 4

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

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.

Upvotes: 1

BadPiggie
BadPiggie

Reputation: 6359

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

Upvotes: 0

Related Questions