Last updated: Feb 28, 2024
Reading timeยท2 min
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.
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 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
.
number
type when typing numbers in TypeScriptTo 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, convert
the object type to a primitive number
by passing it to the Number()
function.
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
.
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.
You can learn more about the related topics by checking out the following tutorials: