In this tutorial, I am gonna show you how to type a date object in TypeScript. There are various ways to do so, but in this instruction, I will show the two most basic ones.
Type a date object in TypeScript
Method 1: Only the newDate() method
We might have been very familiar with using the newDate method to declare a date object. Obviously, when we declare an object that way, we do not have to explicitly type it. TypeScript will automatically understand it as a Date object thanks to the inline assignment.
Syntax:
var date = new Date();
Parameters:
- new Date(): Use the current date and time to create a new date object.
Let’s apply that to create and type our date object:
var myDate = new Date();
console.log(myDate);
console.log(typeof myDate);
Output:
Wed Sep 28 2022 01:14:32 GMT+0700 (Indochina Time)
object
Method 2: Using the ‘Date’ type
The process of explicitly typing the ‘Date’ type is just the same as other types:
variable : type
Example 1:
var myDate : Date = new Date();
console.log(myDate);
Output:
Wed Sep 28 2022 01:12:59 GMT+0700 (Indochina Time)
Please notice that new Date() and Date() are two different methods. If we use newDate(), we will get a Date object. On the other side, the Date() method will return a string.
var myDate = new Date();
var date = Date();
console.log(myDate);
console.log(typeof myDate);
console.log(date);
console.log(typeof date);
Output:
Wed Sep 28 2022 01:34:13 GMT+0700 (Indochina Time)
object
Wed Sep 28 2022 01:34:13 GMT+0700 (Indochina Time)
string
Therefore, if we try to type the Date when using Date():
var myDate : Date = new Date();
var date : Date = Date();
console.log(myDate);
console.log(typeof myDate);
console.log(date);
console.log(typeof date);
Everything will run perfectly, except for line 2 in which you will get this error:
type 'string' is not assignable to type 'Date'
This means that our variable’s is a string and cannot be assigned to type ‘Date’.
Summary
In this tutorial, we have shown two of the most common methods to type a date object in TypeScript. Since we have the inline assignment in TypeScript, we do not have to explicitly type the object. JavaScript will automatically understand its type. But if you still want to type it, then do it the same way as you would with other types.
Maybe you are interested:

Hello. My name is Khanh Hai Ngo. I graduated in Information Technology at VinUni. My advanced programming languages include C, C++, Python, Java, JavaScript, TypeScript, and R, which I would like to share with you. You will benefit from my content.
Name of the university: VinUni
Major: EE
Programming Languages: C, C++, Python, Java, JavaScript, TypeScript, R