0
0
Typescriptprogramming~3 mins

Why Class property declarations in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could avoid messy code and bugs just by declaring your class properties clearly from the start?

The Scenario

Imagine you are building a program to manage a library. You want to keep track of each book's title, author, and number of pages. Without class property declarations, you have to manually create and manage these properties inside the constructor or methods, which can get messy and confusing.

The Problem

Manually adding properties inside the constructor means repeating code and risking mistakes like typos or forgetting to initialize a property. It also makes your code longer and harder to read, especially when you have many properties to manage.

The Solution

Class property declarations let you define all the properties your class will have right at the top. This makes your code cleaner, easier to understand, and reduces errors because you clearly see what data each object will hold.

Before vs After
Before
class Book {

  title: string;
  author: string;
  pages: number;

  constructor(title: string, author: string, pages: number) {
    this.title = title;
    this.author = author;
    this.pages = pages;
  }
}
After
class Book {
  title = '';
  author = '';
  pages = 0;

  constructor(title: string, author: string, pages: number) {
    this.title = title;
    this.author = author;
    this.pages = pages;
  }
}
What It Enables

It enables you to write clearer and safer classes that are easier to maintain and understand.

Real Life Example

Think of a contact app where each contact has a name, phone number, and email. Declaring these properties upfront helps you quickly see what information each contact holds and avoid mistakes when adding new contacts.

Key Takeaways

Declaring class properties upfront makes your code cleaner.

It reduces errors by clearly showing what data each object holds.

It helps maintain and understand your code better as it grows.