In the last chapter, we strongly-typed variables and functions using primitive types. In this chapter, 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 chapter. Let’s expore using this type using the code editor below:

πŸ‘‰ Click the Open Sandbox button to open the editor in a new browser tab.

πŸ‘‰ 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.