0
0
Typescriptprogramming~3 mins

Why Parameter properties shorthand in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could cut your class code in half with just a small change?

The Scenario

Imagine you want to create a class that stores some information, like a person's name and age. You write a constructor and then separately declare and assign each property inside it.

The Problem

This manual way means writing a lot of repeated code: declaring properties, assigning them inside the constructor. It's slow, boring, and easy to make mistakes like forgetting to assign a property.

The Solution

Parameter properties shorthand lets you declare and assign properties right in the constructor parameters. This means less code, fewer errors, and cleaner classes.

Before vs After
Before
class Person {
  name: string;
  age: number;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
After
class Person {
  constructor(public name: string, public age: number) {}
}
What It Enables

You can write concise, clear classes that automatically create and assign properties, saving time and reducing mistakes.

Real Life Example

When building a user profile in an app, you can quickly define user details without extra code clutter, making your code easier to read and maintain.

Key Takeaways

Parameter properties combine declaration and assignment in one step.

This reduces repetitive code in class constructors.

It helps keep your code clean and less error-prone.