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)?
Type ‘undefined’ is not assignable to type ‘number | null’: This is for type x assigned as undefined. Type ‘null’ is not assignable to type ‘number’: This is for type z assigned as null. With this, we conclude our topic ‘TypeScript Nullable’.
Type 'undefined' is not assignable to type 'string'. This happens because TypeScript expects a specific value type but you’re providing an incorrect value type. If you like to learn more about JavaScript value types, feel free to check out this article, “ JavaScript data types: Intro “.
Type 'undefined' is not assignable to type 'number'. (2345) We might look at other libraries, to see what they do, Sanctuary, for instance, has it as:
But TypeScript keeps throwing: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined' is not assignable to type 'number'. I already tried to wrap the call with an if statement checking if externalId && typeof externalId === 'number', but I can't make the error go away.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With