0
0
Typescriptprogramming~5 mins

Parameter properties shorthand in Typescript

Choose your learning style9 modes available
Introduction

This helps you write shorter code when creating classes. It lets you make and save properties in one step.

When you want to create a class and set its properties quickly.
When you want to avoid writing extra lines for property declarations and assignments.
When you want cleaner and easier-to-read class constructors.
When you want to save time writing simple classes with many properties.
Syntax
Typescript
class ClassName {
  constructor(private propertyName: Type, public anotherProperty: Type) {
    // No need to write this.propertyName = propertyName;
  }
}

Use public, private, or protected before the parameter to create a property automatically.

This shorthand only works inside the constructor parameters.

Examples
This creates a class with name as a public property and age as a private property.
Typescript
class Person {
  constructor(public name: string, private age: number) {}
}
This creates a class with brand as a protected property and year as a public property.
Typescript
class Car {
  constructor(protected brand: string, public year: number) {}
}
This creates a class with a single public property title.
Typescript
class Book {
  constructor(public title: string) {}
}
Sample Program

This program creates a User class using parameter properties shorthand. It sets username as public and password as private. Then it prints the username.

Typescript
class User {
  constructor(public username: string, private password: string) {}

  showUsername() {
    console.log(`Username: ${this.username}`);
  }

  // Password is private, so no direct access outside
}

const user = new User('alice', 'secret123');
user.showUsername();
OutputSuccess
Important Notes

Parameter properties shorthand saves you from writing extra lines like this.property = property;.

Private and protected properties cannot be accessed outside the class.

Use this shorthand only for simple property assignments in constructors.

Summary

Parameter properties shorthand lets you create and assign class properties in one step inside the constructor.

Use public, private, or protected before constructor parameters to make properties.

This makes your class code shorter and easier to read.