'Type 'string' is not assignable to type 'number'.ts(2322)

I'm new at typescript and trying to figure out how to handle this error. I understand why it happens, but can't find the right way to handle this.

export function intToString(num: number): string {
  num = num.toString().replace(/[^0-9.]/g, ``);

  if (num < 1000) {
    return num;
  }

  const si = [
    { v: 1e3, s: `K` },
    { v: 1e6, s: `M` },
    { v: 1e9, s: `B` },
    { v: 1e12, s: `T` },
    { v: 1e15, s: `P` },
    { v: 1e18, s: `E` },
  ];

  let index;
  for (index = si.length - 1; index > 0; index--) {
    if (num >= si[index].v) {
      break;
    }
  }

  return (
    (num / si[index].v).toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, `$1`) +
    si[index].s
  );
}

ERROR:

(parameter) num: number
Type 'number' is not assignable to type 'string'.ts(2322)


Solution 1:[1]

The problem is mainly due to this part here. You are returning "num", which is a number type from your input. But your function is expecting a string type output here.

if (num < 1000) {
    return num;
}

This should solve it instead. Just return num.toString() instead. Also, the usage of Math.abs here is to cover the use case of negative values

export function intToString(num: number): string {
  const absNum = Math.abs(num);

  if (absNum < 1000) {
    return num.toString();
  }

  // console.log('test')

  const si = [
    { v: 1e3, s: `K` },
    { v: 1e6, s: `M` },
    { v: 1e9, s: `B` },
    { v: 1e12, s: `T` },
    { v: 1e15, s: `P` },
    { v: 1e18, s: `E` },
  ];

  let index;
  for (index = si.length - 1; index > 0; index--) {
    if (absNum >= si[index].v) {
      break;
    }
  }

  return (
    (num / si[index].v).toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, `$1`) +
    si[index].s
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1