0
0
Typescriptprogramming~5 mins

Class property declarations in Typescript

Choose your learning style9 modes available
Introduction

Class property declarations let you create variables inside a class to store data about each object.

When you want to keep track of information about an object, like a person's name or age.
When you need to set default values for data inside a class.
When you want to organize related data and behavior together in one place.
When you want to create multiple objects with similar properties but different values.
Syntax
Typescript
class ClassName {
  propertyName: type;
  propertyNameWithDefault: type = defaultValue;
}

Properties are declared inside the class but outside any method.

You can give properties a type and optionally a default value.

Examples
This class has two properties: name and age, both declared with types.
Typescript
class Person {
  name: string;
  age: number;
}
Properties have default values set when the object is created.
Typescript
class Car {
  brand: string = "Toyota";
  year: number = 2020;
}
The pages property is optional, marked by ?.
Typescript
class Book {
  title: string;
  pages?: number;
}
Sample Program

This program creates a Dog class with a name property set by the constructor and an age property with a default value. It shows how to access properties and call a method.

Typescript
class Dog {
  name: string;
  age: number = 3;

  constructor(name: string) {
    this.name = name;
  }

  bark() {
    console.log(`${this.name} says Woof!`);
  }
}

const myDog = new Dog("Buddy");
console.log(myDog.name);  // Buddy
console.log(myDog.age);   // 3
myDog.bark();             // Buddy says Woof!
OutputSuccess
Important Notes

Class properties can be public (default), private, or protected to control access.

Default values are used if no value is given when creating an object.

Optional properties may be undefined if not set.

Summary

Class properties store data inside objects created from the class.

You declare properties with a name and type, and can give default values.

Properties help organize and keep track of information related to each object.