Last updated: Mar 19, 2022
Photo from Unsplash
The error "Operator '+' cannot be applied to types 'Number' and 'number'"
occurs when we use the
Number type instead of
solve the error, make sure to use the
number type with lowercase
n in your
Here is an example of how the error occurs.
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
which caused the error.
We can't use the addition operator (+) to add the non-primitive object type to a
value of type
To solve this, always use the
number type when typing numbers in TypeScript.
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.
// 👇️ 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
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
const num = 100 as Number; console.log(+num + 100);
The error was caused because there is a difference between the primitive
boolean types and the non-primitive
The non-primitive types are objects and should never be used when typing values in TypeScript.
TypeScript best practices
documentation warns to never use the
Object non-primitive objects when typing values in your TypeScript code.
Instead, you should be using
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
(object type) and
number (primitive type). To solve the error, always use the
number primitive type in your TypeScript code.