Learn TypeScript

Using the Date type

Using the Date type

In the last module, we strongly-typed variables and functions using primitive types. In this module, we will use some other common types that are available in TypeScript. We'll start by exploring the Date type in this lesson.

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.

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