Home > Blockchain >  Typescript - Argument of type 'HTMLTableRowElement | null is not assignable to parameter of typ
Typescript - Argument of type 'HTMLTableRowElement | null is not assignable to parameter of typ

Time:05-09

In my Angular application, I am trying to access the DOM to scroll a table row into view. For this purpose, I have created a method and pass in the following parameter:

this.scrollIntoView(this.tableElement?.rows.item(this.tableComponent.index));

Apparently the parameter can be null and undefined and I am getting the following typescript error:

TS2345: Argument of type 'HTMLTableRowElement | null | undefined' is not assignable to parameter of type 'HTMLElement'.   Type 'undefined' is not assignable to type 'HTMLElement'.

The method scrollIntoView(row: HTMLElement) accepts an HTMLElement as input. The this.tableElement is an HTMLTableElement. And apparently the issue is that I pass in a row into this.scrollintoView() that could be null.

I have tried to avoid this issue by simply placing my method this.scrollIntoView() into an if-block, which checks if the parameter is null or undefined:

  if (
    this.tableElement?.rows.item(this.tableComponent.index) !== null &&
    this.tableElement?.rows.item(this.tableComponent.index) !== undefined
  ) {

Well. None of this helps. I don't know what the issue is and would really appreciate some help!

CodePudding user response:

The message looks like a compiler message based on incorrect variable types, so I think the error occurs before your condition runs.

I suspect you have to do this:

scrollIntoView(row: HTMLTableRowElement | null | undefined)

And change the value you're passing into the function so that it isn't an HTMLTableElement.

This is a bit of a guess since you didn't tell us what tableElement is, nor did you share any code from your scroll method.

CodePudding user response:

I have to fight TypeScript on things like this a lot. I would usually do:

this.scrollIntoView(this.tableElement?.rows.item(this.tableComponent.index) as HTMLTableRowElement);

  • Related