0
0
Typescriptprogramming~15 mins

Why typed classes matter in Typescript - See It in Action

Choose your learning style9 modes available
Why typed classes matter
📖 Scenario: Imagine you are building a simple app to manage books in a library. You want to keep track of each book's title and number of pages. Using typed classes helps you avoid mistakes and makes your code easier to understand.
🎯 Goal: You will create a typed class called Book with properties for title and pages. Then you will create an instance of this class and print its details.
📋 What You'll Learn
Create a class called Book with typed properties title: string and pages: number
Add a constructor to Book that sets title and pages
Create an instance of Book called myBook with title 'The TypeScript Guide' and pages 250
Print the book's title and pages using console.log
💡 Why This Matters
🌍 Real World
Typed classes are used in apps to keep data organized and safe, like managing books, users, or products.
💼 Career
Understanding typed classes is important for writing reliable TypeScript code in many software development jobs.
Progress0 / 4 steps
1
Create the typed class
Create a class called Book with typed properties title: string and pages: number. Add a constructor that takes title: string and pages: number and sets them to the class properties.
Typescript
Need a hint?

Use class keyword, declare properties with types, and write a constructor method.

2
Create an instance of the class
Create an instance of Book called myBook with title 'The TypeScript Guide' and pages 250.
Typescript
Need a hint?

Use new Book('The TypeScript Guide', 250) and assign it to myBook.

3
Access and print properties
Use console.log to print the book's title and pages from the myBook instance. Print the title first, then the pages.
Typescript
Need a hint?

Use console.log(myBook.title) and console.log(myBook.pages).

4
Final output
Run the program to print the book's title and pages exactly as shown: first line The TypeScript Guide, second line 250.
Typescript
Need a hint?

Make sure you run the program and see the two lines printed exactly.