The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type
Here is another example of this error occurring that might help people.
If you're using typescript and trying to compute the difference between dates (In my case I was attempting to use ISO string from database):
new Date("2020-03-15T00:47:38.813Z") - new Date("2020-03-15T00:47:24.676Z")
TypeScript Playground
It will show the error.
However, this same exact code works if you put it in the browser console or other node environment
new Date("2020-03-15T00:47:38.813Z") - new Date("2020-03-15T00:47:24.676Z")
14137
I may be wrong, but I believe this works due to the -
operator implicitly using valueOf
on each of it's operands. Since valueOf
on Date returns a number
the operation works.
However, typescript doesn't like it. Maybe there is a compiler option for this is forcing this constrain and I'm not aware.
new Date().valueOf()
1584233296463
You can fix by explicitly making the operands number (bigint) types so the -
works.
Fixed Example
new Date("2020-03-15T00:47:38.813Z").valueOf() - new Date("2020-03-15T00:47:24.676Z").valueOf()
TypeScript Playground
Number
should be lowercase: number
.
- See sample on Playground
- Documentation for basic types