eric_heim
eric_heim

Reputation: 61

Passing no parameters to a function in TypeScript

const range = (...myData: number[]) => {
  myData.sort();
  return myData[myData.length-1] - myData[0];
}

Codecademy says "Although the type for the rest parameter is an array of numbers, calling range() with no argument is perfectly valid and generates no TypeScript error. However, a value of NaN will be returned."

I thought TypeScript gives an error if we don’t provide a value for the arguments of a function, unless they have a ? after their name.

Upvotes: 0

Views: 1279

Answers (2)

I believe you should expect at least one argument, because undefined - undefined = NaN

const range = <N extends number, Data extends N[]>(...myData:[N,...Data]) => {
  myData.sort();
  return myData[myData.length-1] - myData[0];
}

range() // error
range(2) // ok
range(2,3) // ok

Here you can find some docs If you want to be super safe, turn on all strict flags in your tsconfig. In this case, you can consider noUncheckedIndexedAccess flag

Upvotes: 0

Lucas D
Lucas D

Reputation: 465

The rest parameter is special. See here how it works in plain JS. Arguments given as rest parameters are put into a JS Array. If you omit the arguments then an empty array is given as the rest parameter.

Upvotes: 2

Related Questions