0
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.

2
  • 1
    ...myData: number[] means zero or more numbers, each as separate parameters, not 1 or more. Are you looking for ways to change the type to force there to be at least 1 number? or are you looking to modify the code to return something other than NaN when given zero? Commented Jun 23, 2021 at 2:40
  • 1
    A rest parameter is an array of the remaining parameters that weren't previously defined in the function. They can be empty (i.e. no arguments at the point of the parameter, e.g. range(), in which case myData: number[] = [] -> myData.length === 0), or they can contain values (i.e. one of more arguments at the point of the parameter, e.g. range(1, 2, 3), in which case myData: number[] = [1, 2, 3] -> myData.length === 3). The reason range() returns NaN is because: myData[-1] - myData[0] -> undefined - undefined === NaN Commented Jun 23, 2021 at 2:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.