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.
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
.
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.