How do I express a date type in TypeScript?

Viewed 556179

How do I express dates in TypeScript? Dates aren't a TypeScript type, so do I use any or object? Seems like there would be a "right" way to do:

let myDate: any = new Date();

I couldn't find much on Google, despite it being such a simple question.

4 Answers

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;

As others have mentioned the type is Date.

This type is usefull when you want to enforce at compile time that you really have a Date object. Below is a mistake that is often make (forgetting the new keyword) and we can see that it is caught at compile time.

const date: Date = new Date();

function logDayNumber(date: Date){
    console.log(date.getDay())
} 

// Works fine
logDayNumber(date);

// Compile time error which happens when you forget new a String we be produced from Date()
// Argument of type 'string' is not assignable to parameter of type 'Date'
logDayNumber(Date());
Related