Home > Back-end >  Define type for array of array or number and use spread operator
Define type for array of array or number and use spread operator

Time:04-23

I am trying to figure out how to define type for Array which has both Array and a number.

input: [[2,7,11,15], 9]

// I tried
input: Array<Array<number> | number>

However, when I use this with spread operator then it throws an error A spread argument must either have a tuple type or be passed to a rest parameter.

tests.forEach((test) => {
  console.log(twoSumHashMap(...test.input))
})

const twoSumHashMap = (nums, target) => {
  let map = new Map(), required;

  for(let i = 0; i<nums.length; i  ) {
    required = target - nums[i];
    if(map.has(required)) {
      return [map.get(required), i]
    } else {
      map.set(nums[i], i);
    }
  }
}
const tests: Array<{input: Array<Array<number> | number>, expected: Array<number>}> = [
  {input: [[2,7,11,15], 9], expected: [0,1]},
  {input: [[3,2,4], 6], expected: [1,2] },
  {input: [[3,3], 6], expected: [0,1] }
]

Workaround

Perhaps I don't need to use spread operator here and can simply use this since input will always be 2 element.

tests.forEach((test) => {
  console.log(twoSumHashMap(test.input[0], test.input[1]))
})

Is there a better pattern to use typescript here?

CodePudding user response:

The twoSumHashMap expects only two arguments. Arrays might have sizes other then 2, so you should explicitly type input as a tuple with two items (TS playground):

input: [number[], number]

Your function should also have a return value if it can't find two numbers, and types for the inputs (TS playground):

const twoSumHashMap = (nums: number[], target: number) => {
  const map = new Map();

  for(let i = 0; i<nums.length; i  ) {
    const required = target - nums[i];
    
    if(map.has(required)) {
      return [map.get(required), i]
    }
    
    map.set(nums[i], i);
  }

  return [null, -1];
}
  • Related