Borislav Hadzhiev
Mon Mar 07 2022·2 min read
Photo by Chad Madden
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.
// 👇️ 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.
// 👇️ 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.
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
.
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.
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.
Date
.A good way to check the type of something in TypeScript is to assign is to a variable and hover over the variable.
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.
const date = new Date('2023-09-24'); console.log(date.getFullYear()); // 👉️ 2023 console.log(date.getMonth()); // 👉️ 8 console.log(date.getDate()); // 👉️ 24