TypeScript Version:
1.8.9
Code
"use strict";
let start = new Date()
let end = new Date()
console.log(start - end)
Expected behavior:
print the difference between two date
Actual behavior:
don't compile when compile option noEmitOnError is enabled.
Here is the error message:
app.ts(5,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
app.ts(5,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
TS doesn't understand valueOf, so it doesn't consider Date to be intrinsically convertible to number for arithmetic operations. You have to be explicit with end.getTime() - start.getTime()
Explicitly coercing to a number with + also works.
"use strict";
let start = new Date()
let end = new Date()
console.log(+start - +end)
@Arnavion @weswigham thanks
A more explicit way to coerce to a Number is to use Number:
Number(new Date())
Most helpful comment
Explicitly coercing to a number with
+also works.