Home > Blockchain >  How to persuade typescript to accept that array isn't empty?
How to persuade typescript to accept that array isn't empty?

Time:10-17

I have simple code construction:

const arr: number[] = [1];
while (arr.length > 0) {
   const current: number = arr.pop();
   ...
}

Typescript argues (to "const cutrent") that "Type 'number | undefined' is not assignable to type 'number'" Obviously from condition of "while" that the variable "current" is always number (not undefined). How to explain it to typescript without ugly work arounds?

CodePudding user response:

Try this:

const current: number = arr.pop() as number;
  • Related