0 of 6 problems solved0%
3 of 6

Sum Numbers from Unknown

When input is unknown, check first. Only treat it as a number[] when it really is an array of numbers. If not, return 0.

This shows how unknown guides you to safe code, while any would let you call array methods blindly.

function avg(x: unknown) {
  if (Array.isArray(x) && x.every((n) => typeof n === "number")) {
    const sum = x.reduce((a, b) => a + b, 0);
    return x.length ? sum / x.length : 0;
  }
  return 0;
}

Your Task

Compute the sum of an unknown value only when it is a number array.

  • Write function sumNumbers(x: unknown): number.
  • If x is an array and every item is a number, return the sum; otherwise return 0.
  • Return 0 for an empty array.
  • Avoid mutation.