Learn TypeScript
Using the Date type
Using the Date type
In this lesson, we will explore the Date type.
Exploring the Date type
We have briefly met the Date type in the last module. Let's explore this.
- Copy and paste the code below into the editor:
const dateOfBirth = new Date(1990, 4, 7);If we assign a variable to the JavaScript Date constructor, TypeScript infers its type to be Date.
The
Datetype is a representation of the Date object in JavaScript.
- Enter the following code into the editor beneath the
dateOfBirthdeclaration. Manually type the code rather than copying and pasting.
console.log(dateOfBirth.getDate());Notice how the editor provides intellisense.
Nice!
- Copy and paste the code below into the editor:
console.log(dateOfBirth.addDays(2));🤔
A type error is raised. What is the problem?
Type annotations can be used for dates as well.
- Copy and paste the code below into the editor:
function calculateRenewal(startDate) { const result = new Date(startDate); result.setDate(result.getDate() + 30); return result;}- Add type annotations to the function so that
startDateis aDate, and the function return type is alsoDate.
Summary
The Date type lets us strongly-type date variables and gain useful intellisense on the JavaScript Date object.
Next up, we'll learn about the any type.
