Typescript: Can't minus two Date object

Created on 23 Apr 2016  ·  4Comments  ·  Source: microsoft/TypeScript

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

Most helpful comment

Explicitly coercing to a number with + also works.

"use strict";

let start = new Date()
let end = new Date()
console.log(+start - +end)

All 4 comments

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())
Was this page helpful?
0 / 5 - 0 ratings