How to express a Date Type in TypeScript ?
Last Updated :
15 Dec, 2023
In this tutorial, we will learn about expressing the date type in TypeScript. Generally, In JavaScript, the classes can be used to add types similarly in TypeScript the classes, type alias, and the interfaces can also be used to add types to the variables.
Some ways of expressing date type in TypeScript are listed below:
Without specifying any of the types
In TypeScript, if we do not provide a Date type to the Date object, then it will type it using the internal inference as the Date object returns the date as a result. By default, the date object returns the current date if there is no parameter passed to it to get the particular date and time.
Syntax:
const date = new Date();
Example: The below example shows how the Date object will behave if no type is provided to it.
Javascript
const currDate = new Date();
const dateStr: string = currDate.toDateString();
console.log(dateStr);
|
Output:
Thu Dec 14 2023
Manually Typing Date Object
We can also type the date object manually using the Date type. It is the same type that gets inferred automatically by TypeScript when we do not specify any type.
Syntax:
const date: Date = new Date();
Example: The below code example types the date object to he Date type by specifying it manually.
Javascript
const currDate: Date = new Date();
const dateStr: string = currDate.toDateString();
console.log(dateStr);
|
Output:
Thu Dec 14 2023
Using type alias or interface for typing
In this approach, we will first define an interface or an type alias with a property of Date type and then use those created types to type the actual date object we will create using the new Date().
Syntax:
// Using type alias to type date object
type type_name = Date;
const currDate: type_name = new Date()
// Using interface to type date object
interface interface_name{
interface_prop: Date;
}
const currDate: interface_name = {
today: new Date(),
}
Example: The below example will show the use of the interface and the type alias to type the date object in TypeScript.
Javascript
type myDate = Date;
const currentDate: myDate = new Date();
console.log(currentDate.toDateString());
interface dateInterface {
today: Date;
}
const currDate: dateInterface = {
today: new Date(),
}
console.log(currDate.today.toDateString());
|
Output:
Thu Dec 14 2023
Thu Dec 14 2023
Share your thoughts in the comments
Please Login to comment...