How to type a Date object in TypeScript

avatar

Borislav Hadzhiev

Mon Mar 07 20222 min read

banner

Photo by Chad Madden

Typing a Date object in TypeScript #

Use the Date type to type a Date object in TypeScript, e.g. const date: Date = new Date(). The Date() constructor returns an object that has a type of Date. The interface defines typings for all of the built-in methods on the Date object.

index.ts
// 👇️ const date: Date const date: Date = new Date();

The Date() constructor returns an object that has a type of Date.

If you are using an inline assignment, like in the example, you can let TypeScript infer its type.

index.ts
// 👇️ const date: Date const date = new Date();

You would type a Date object in the same way when using an interface or a type alias.

index.ts
interface Delivery { shippingDate: Date; } const shippingDate = new Date('2023-09-24'); const obj: Delivery = { shippingDate, };

The shippingDate property on the Delivery interface has a type of Date.

To get a Date object, you have to use the Date() constructor.

If you hover over the Date() constructor, you can see that it returns an object of type Date when instantiated with the new operator.

index.ts
interface DateConstructor { new(): Date; new(value: number | string): Date; new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; }

The Date() constructor can be called without any parameters (to get the current date), it could be called with a number or string, or with multiple, comma-separated numbers for the year, month, date, etc.

In all of the overloads, the constructor returns an object of type Date.

A good way to check the type of something in TypeScript is to assign is to a variable and hover over the variable.

index.ts
const date = new Date();

When using inline assignment, TypeScript is able to infer the type of the value on the right-hand side.

The Date type is defined as an interface and contains typings for all of the date-related built-in methods.

index.ts
const date = new Date('2023-09-24'); console.log(date.getFullYear()); // 👉️ 2023 console.log(date.getMonth()); // 👉️ 8 console.log(date.getDate()); // 👉️ 24
Use the search field on my Home Page to filter through my more than 1,000 articles.