Operator '+' cannot be applied to types 'Number' and number

avatar

Borislav Hadzhiev

Last updated: Mar 19, 2022

banner

Photo from Unsplash

Operator '+' cannot be applied to types 'Number' and number #

The error "Operator '+' cannot be applied to types 'Number' and 'number'" occurs when we use the Number type instead of number (lowercase n). To solve the error, make sure to use the number type with lowercase n in your TypeScript code.

operator plus cannot be applied to types number

Here is an example of how the error occurs.

index.ts
const num: Number = 100; // ⛔️ Error: Operator '+' cannot be applied // to types 'Number' and 'number'.ts(2365) console.log(num + 100);

We used the Number, non-primitive object type to type the num variable, which caused the error.

We can't use the addition operator (+) to add the non-primitive object type to a value of type number.

To solve this, always use the number type when typing numbers in TypeScript.

index.ts
const num: number = 100; console.log(num + 100); // 👉️ 200

The type in the example can be inferred based on the provided value, so we don't even have to set it.

index.ts
// 👇️ const num: 100 const num = 100; console.log(num + 100); // 👉️ 200

We used the primitive number type which resolved the error.

If you don't have access to the code that uses the Number object type, you can convert the object type to a primitive number by passing it to the Number() function.

index.ts
const num = 100 as Number; console.log(Number(num) + 100); // 👉️ 200

You might also see examples online that use the unary plus (+) operator to convert a value to a number.

index.ts
const num = 100 as Number; console.log(+num + 100);

The error was caused because there is a difference between the primitive number, string and boolean types and the non-primitive Number, String, Boolean, Object, etc.

The non-primitive types are objects and should never be used when typing values in TypeScript.

The TypeScript best practices documentation warns to never use the Number, String, Boolean, Symbol or Object non-primitive objects when typing values in your TypeScript code.

Instead, you should be using number, string, boolean, symbol and Record types.

Conclusion #

The error "Operator '+' cannot be applied to types 'Number' and number" means that we are trying to use the addition operator with values of type Number (object type) and number (primitive type). To solve the error, always use the number primitive type in your TypeScript code.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.