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.

TypeScriptOpen exercise in CodeSandbox
  • 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 Date type is a representation of the Date object in JavaScript.

  • Enter the following code into the editor beneath the dateOfBirth declaration. 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 startDate is a Date, and the function return type is also Date.

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.

© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more