简体   繁体   中英

Get rid of type: any in method

maybe you can help me out here.

So I would like to get rid of the any types in the descendingComparator method and replace them with the appropriate type. I'm stuck at the moment and would be grateful for any help.

function descendingComparator(a: any, b: any, orderBy: string) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

function getComparator(order: string, orderBy: string) {
  return order === 'desc'
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

How i use it:

{stableSort(rows, getComparator(order, orderBy)) ...}

Thank you!

If this is meant to be comparing numbers, then something like this:

function descendingComparator(
   a: { [x: string]: number },
   b: { [x: string]: number },
   orderBy: string
) {
...
}

and you can type a and b in getComparator similarly.

If this is meant to be comparing an unknown but consistent type then something like this:

function descendingComparator<T>(
   a: { [x: string]: T },
   b: { [x: string]: T },
   orderBy: string
) {
...
}

and again you can type getComparator similarly.

If I understand the problem then you can do something like:

function descendingComparator<T extends object, TOrder extends keyof T>(a: T, b: T, orderBy: TOrder) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

Use like:


const a = {
    x: 1
};

const b = {
    x: 2
};

descendingComparator(a, b, 'x'); // works
descendingComparator(a, b, 'y'); // needs to be 'x' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM