AI Hints
TypeScript · Lesson 45 of 120

Parameter Properties

Less typing.

⏱ 2 min read▶ Video at 35:53🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Declaring a property, then assigning it in the constructor, is a lot of repetition. Parameter properties do both at once. Just add a modifier in front of the constructor parameter.

Parameter Properties
From the video: Parameter Properties
  • Declare and assign
  • Repetitive
  • Do both at once

Shorter classes

Adding public readonly and private in front of the parameters creates the properties, and assigns them, automatically. Run it.

app.tstypescript
class Customer {
  constructor(
    public readonly name: string,
    private email: string,
  ) {}

  contact(): string {
    return `${this.name} <${this.email}>`;
  }
}

const c = new Customer("Sam", "sam@example.com");
console.log(c.contact(), "|", c.name);
Output
Sam <sam@example.com> | Sam

Summary

Modifiers in front of constructor parameters declare and assign properties in one go. Next, implementing interfaces.

Key takeaways
  • public readonly name
  • private email
  • Less code
Next up: Implementing Interfaces — a contract