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

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
2 min

banner

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

# Always use the number type when typing numbers in TypeScript

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 code for this article is available on GitHub

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

implicitly typing the variable

We used the primitive number type which resolved the error.

# Convert the object type to a primitive

If you don't have access to the code that uses the Number object type, 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 code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev