Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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)?

like image 512
devinbost Avatar asked Jun 17 '19 21:06

devinbost


People also ask

Is null assignable in typescript?

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’.

Why does typescript say undefined type is not assignable?

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 “.

Is it possible to assign undefined type to numbers?

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:

Is argument of type'number | undefined'assignable to parameter?

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.


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;

like image 81
gatsbyz Avatar answered Nov 14 '22 22:11

gatsbyz