13

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
  • 3
    .pop() returns undefined if the array is empty. Commented Jun 17, 2019 at 21:14

1 Answer 1

9

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;

Sign up to request clarification or add additional context in comments.

3 Comments

I have !== undefined check in place and still get that error :/
Any solutions to the problem raised by @jayarjo?
@Nyxynyx a = myArr.pop() as number;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.