Home > Net >  Angular - Type '"desc"' is not assignable to type 'null'
Angular - Type '"desc"' is not assignable to type 'null'

Time:09-26

In Angular-12, I am trying to sort a table using:

sortData = {        //Current Sort Data
  "col" : null,
  "order" : null
}

sort(col: any){
  if(this.sortData.order=="asc" && this.sortData.col==col){
    this.sortData.order = "desc"
  } else if(this.sortData.order=="desc" && this.sortData.col==col){
    this.sortData.order = null;
    col = null;
  } else {
    this.sortData.order = "asc"
  }
  this.sortData.col = col;
  this.ngOnInit();
}

I got this error:

Type '"desc"' is not assignable to type 'null'.

With this line highlighted:

this.sortData.order = "desc"

this.sortData.order = "asc"

How do I sort this out?

Thanks

CodePudding user response:

Best solution is to define a class and declare the type of your object as that class:

export class SortDataModel {
  col: any;          \\ your desired type: string, number,...
  order: any;        \\ your desired type: string, number,...
}

Then define your variable:

public sortData: SortDataModel = {
  col: null,
  order: null
}

Another way is to define your variable type as any to bypass the type error. but I don't recommend it myself:

public sortData: any = {
  col: null,
  order: null
}

CodePudding user response:

You can do something like this:


sortData : { col: null | string, order: null | string} = {        //Current Sort Data
  "col" : null,
  "order" : null
}

This will pass the null type check. Also, it seems the code is fine and should not generate any errors if it is please add more code to the question and/or debugging details.

Note: You should understand the lifecycle methods are being called implicitly by angular. You shouldn't do that, if you want to call the logic of onInit multiple times, try separating it in a new function.

  • Related