2

I am trying to create a simple function that finds the smallest two integers in a given array. New to typescript but good with Javascript, I am wondering why would typescript complains about adding two numbers:

const array: Number[] = [
  2, 3, 4, 2, 4, 3, 5, 2, 5, 91, 2, 4, 32, 43, 3, 5, 3435,
];

const twoSmallest = (array: Number[]): Number[] => {
  if (array.length < 2) return array;

  const maxSum = array.reduce((acc: Number, curr: Number):Number => {
    return curr + acc;
  }, 0);

  for (let i = 0; i < array.length; i++) {
    //About to add my rest of the code here
  }
};

console.log('Result = ', twoSmallest(array));

Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62

1 Answers1

5

Number is the type for something created using the Number constructor, eg

const someNum = new Number(123);

which has odd repercussions and should almost never be used.

For plain numbers - which one should be using 99% of the time - you want just number instead, eg

const array: number[] = [
  2, 3, 4, 2, 4, 3, 5, 2, 5, 91, 2, 4, 32, 43, 3, 5, 3435,
];

Replace all your Number with number and it'll work as desired.

You can also remove the explicit annotations when not necessary, and TypeScript will infer them for you - less manual annotations means less chance of accidentally typing something wrong.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I get that. Thank you very much for your explanation. Btw when you say explicit annotations, you mean while initializing the array right? – Shivam Sahil Aug 06 '21 at 03:31
  • yeah, like `const thing: number = 3`, typescript can infer that so `const thing = 3`. Our linter config at work yells at me to always be explicit anyway, so there are differing styles out there. – Dan Oswalt Aug 06 '21 at 13:08