Menu
Coddy logo textTech

Type Aliases for Objects

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 38 of 73.

TypeScript allows you to create a type alias that defines a reusable shape for objects.

A type alias uses the type keyword to create a named definition for an object structure. Once defined, you can use this alias anywhere you need that specific object shape:

type Product = {
  name: string;
  price: number;
  inStock: boolean;
};

let laptop: Product = {
  name: "Gaming Laptop",
  price: 1299,
  inStock: true
};

let phone: Product = {
  name: "Smartphone",
  price: 699,
  inStock: false
};
challenge icon

Challenge

Easy

Create a type alias named Book for an object with the following properties:

  • title of type string
  • author of type string
  • pages of type number
  • isAvailable of type boolean

Create a type alias named Movie for an object with the following properties:

  • title of type string
  • director of type string
  • duration of type number
  • rating of type string

Using your type aliases, create the following variables:

  • Create a variable named novel of type Book with title "The Great Gatsby", author "F. Scott Fitzgerald", pages 180, and isAvailable true
  • Create a variable named textbook of type Book with title "TypeScript Handbook", author "Microsoft", pages 450, and isAvailable false
  • Create a variable named film of type Movie with title "Inception", director "Christopher Nolan", duration 148, and rating "PG-13"

Create a function named getBookInfo that accepts a parameter of type Book and returns a string in the format "[title] by [author] - [pages] pages".

Create a function named getMovieInfo that accepts a parameter of type Movie and returns a string in the format "[title] directed by [director] ([duration] min)".

Print the following outputs on separate lines:

  • Call getBookInfo with novel and print the result
  • Call getBookInfo with textbook and print the result
  • Call getMovieInfo with film and print the result
  • Print the availability status of novel (the isAvailable property)

Try it yourself

// TODO: Write your code here

// Create type aliases for Book and Movie


// Create variables using the type aliases


// Create functions to get information


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