0
0
Typescriptprogramming~15 mins

Why object types are needed in Typescript - See It in Action

Choose your learning style9 modes available
Why object types are needed
📖 Scenario: Imagine you are building a simple app to keep track of books in a library. Each book has a title, an author, and a year it was published. You want to make sure that every book you add has all these details correctly typed.
🎯 Goal: You will create an object type to describe a book, then create a book object using that type. This helps your program know exactly what information a book should have and avoid mistakes.
📋 What You'll Learn
Create an object type called Book with properties title (string), author (string), and year (number).
Create a variable called myBook of type Book with the exact values: title = "The Great Gatsby", author = "F. Scott Fitzgerald", year = 1925.
Add a variable called isClassic and set it to true if the book year is before 1950, otherwise false.
Print the book title and whether it is a classic in the format: "The Great Gatsby is a classic: true".
💡 Why This Matters
🌍 Real World
Object types are used in real apps to make sure data like user profiles, products, or books have the right information and format.
💼 Career
Knowing object types is important for writing safe and clear code in TypeScript, which many companies use for web development.
Progress0 / 4 steps
1
Create the Book object type
Create an object type called Book with these exact properties: title as string, author as string, and year as number.
Typescript
Need a hint?

Use type Book = { ... } and list the properties with their types inside curly braces.

2
Create a myBook variable of type Book
Create a variable called myBook of type Book and assign it an object with title set to "The Great Gatsby", author set to "F. Scott Fitzgerald", and year set to 1925.
Typescript
Need a hint?

Use const myBook: Book = { ... } and fill in the exact property values.

3
Add a variable isClassic to check if the book is a classic
Add a variable called isClassic and set it to true if myBook.year is less than 1950, otherwise set it to false.
Typescript
Need a hint?

Use a ternary operator or if-else to set isClassic based on myBook.year.

4
Print the book title and if it is a classic
Write a console.log statement to print the book title and whether it is a classic in this exact format: "The Great Gatsby is a classic: true".
Typescript
Need a hint?

Use a template string with console.log to print the message exactly.