DEV Community

Discussion on: Advanced TypeScript Exercises - Answer 3

Collapse
 
jfet97 profile image
Andrea Simone Costa
function f(...[a,b]: string[] | number[]) {
  if (typeof a === 'string') {
    return a + ':' + b; // b is number | string
  } else {
    return a + b; // error both are number | string
  }
}

About this solution you asked: type string[] | number[] doesn't fully fit this function. Can you spot why, and what type would be better?

Let me try: is all about the length of the array? We need exactly two elements, so a tuple should be better, right?

Collapse
 
macsikora profile image
Pragmatic Maciej

Yes exactly, if we have static number of elements then we should use tuple type. Using number[] means we allow any number of arguments of type number.

function f(...[a, b]: number[]) { }
function g(...[a, b]: [number, number]) { }

f(1, 2, 3) // allowed
g(1,2,3) // only two allowed so error