Menu
Coddy logo textTech

Introduction to Interfaces

Part of the Introduction To TypeScript section of Coddy's JavaScript journey. Lesson 39 of 73.

Interfaces serve the same fundamental purpose as type aliases for objects but use a different syntax and offer some unique capabilities.

An interface is declared using the interface keyword followed by the interface name and the object structure in curly braces:

interface Animal {
  name: string;
  sound: string;
}

let dog: Animal = {
  name: "Buddy",
  sound: "Woof"
};

The syntax is clean and straightforward - you simply list the properties and their types within the interface body. Once defined, you can use the interface name as a type annotation anywhere in your code, just like with type aliases.

challenge icon

Challenge

Easy

Create an interface named Pet with the following properties:

  • name of type string
  • species of type string
  • age of type number
  • isVaccinated of type boolean

Create an interface named Vehicle with the following properties:

  • make of type string
  • model of type string
  • year of type number

Using your interfaces, create the following variables:

  • Create a variable named myDog of type Pet with name "Buddy", species "Golden Retriever", age 3, and isVaccinated true
  • Create a variable named myCat of type Pet with name "Whiskers", species "Persian", age 2, and isVaccinated false
  • Create a variable named myCar of type Vehicle with make "Toyota", model "Camry", and year 2022

Create a function named describePet that accepts a parameter of type Pet and returns a string in the format "[name] is a [age]-year-old [species]".

Create a function named getVehicleInfo that accepts a parameter of type Vehicle and returns a string in the format "[year] [make] [model]".

Print the following outputs on separate lines:

  • Call describePet with myDog and print the result
  • Call describePet with myCat and print the result
  • Call getVehicleInfo with myCar and print the result
  • Print the vaccination status of myDog (the isVaccinated property)

Try it yourself

// TODO: Write your code here

// Create the Pet interface

// Create the Vehicle interface

// Create the variables using your interfaces

// Create the describePet function

// Create the getVehicleInfo function

// Print the required outputs
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript

Practice on your own: Online JavaScript compiler