TypeScript - Type 'number | undefined' is not assignable to type 'number'

Viewed 25239

Here is my code:

var a:number;
a = 4;

var myArr: number[];
myArr = [1,2,3];
myArr.push(1);

a = myArr.pop();

When I compile with "module" (in my tsconfig.json file) set to "system" or "amd" to allow me to bundle the output into an "outFile" location, I get this error:

hello-world.ts:23:1 - error TS2322: Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.

a = myArr.pop();

Where is it getting the "undefined" type from? Also, how do I resolve this error without setting "strict" to false (in my tsconfig.json)?

1 Answers

Array.prototype.pop() returns type number or undefined. That's where number undefined comes from.

When you perform pop() on an object, a number is returned when array.length > 0, and undefined is returned if array.length = 0.

You should either check if myArr.pop() !== undefined

-or-

a: number | undefined;

Related