Home > database >  type [...number[], string] remains the same after last element was popped
type [...number[], string] remains the same after last element was popped

Time:10-05

I have an array typed as a tuple with multiple numbers and a string at the end. After popping the last element, I know that the array now contains numbers only, but TypeScript doesn't. How do I help TypeScript understand this?

const mixedArr: [...number[], string] = [1, 2, 3, 'Hello']
const str = mixedArr.pop() as string
mixedArr.forEach(item => {
  item * 2 // causes problems, bc item is seen as string | number
})

CodePudding user response:

You could declare a new local with the correct type:

const numbers = mixedArr as number[];
numbers.forEach(item => item * 2);

CodePudding user response:

Once a variable is declared, you will not be able to change it's type. If you wanted you could set it to type any using any[], or declaring a new variable doing something like let numArr = mixedArr as number[];

CodePudding user response:

The variable is of type string | number, which you can also workaround with switch statement.

const mixedArr: [...number[], string] = [1, 2, 3, 'Hello']
const str = mixedArr.pop() as string
mixedArr.forEach(item => {
  switch(item) {
      case item as number: item * 2;
  }
})
  • Related