- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
Properties and Methods in TypeScript
In TypeScript, properties and methods are key elements of a class that define the structure and behavior of objects. Properties hold data, and methods define the actions that can be performed on the objects. TypeScript's static typing feature provides additional benefits by ensuring that properties and methods are used correctly, enhancing code quality and reducing errors.
Defining Properties
Properties in TypeScript are variables associated with a class that represent the state of an object. You can define properties with specific types, allowing you to ensure type safety.
class Car {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
}
const myCar = new Car("Toyota", "Corolla", 2020);
console.log(myCar.make); // Output: Toyota
In this example:
make
,model
, andyear
are properties of theCar
class.- These properties are typed (
string
,string
,number
) and are initialized via the constructor.
Defining Methods
Methods are functions that belong to a class. They define the behavior of objects created from the class. You can declare methods with specific types for both parameters and return values.
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
calculateArea(): number {
return this.width * this.height;
}
}
const rect = new Rectangle(5, 10);
console.log(rect.calculateArea()); // Output: 50
In this example:
calculateArea
is a method that returns the area of the rectangle.- It is typed to return a
number
, ensuring the correct return type.
Read-Only Properties
TypeScript allows you to define properties that can only be assigned a value once, either during initialization or within the constructor. These are called readonly
properties.
class Product {
readonly name: string;
constructor(name: string) {
this.name = name;
}
}
const product = new Product("Laptop");
console.log(product.name); // Output: Laptop
// product.name = "Smartphone"; // Error: Cannot assign to 'name' because it is a read-only property.
In this example:
- The
name
property isreadonly
, so it cannot be modified after the object is created.
Optional Properties
In TypeScript, you can define optional properties, which may or may not be present in an object. These are denoted by a ?
after the property name.
class Employee {
id: number;
name: string;
department?: string;
constructor(id: number, name: string, department?: string) {
this.id = id;
this.name = name;
if (department) {
this.department = department;
}
}
}
const emp1 = new Employee(1, "John");
const emp2 = new Employee(2, "Jane", "HR");
console.log(emp1.department); // Output: undefined
console.log(emp2.department); // Output: HR
In this example:
- The
department
property is optional (department?
), so it may or may not be provided during object creation.
Method Overloading
Method overloading in TypeScript allows you to define multiple signatures for the same method, where each signature can accept different parameters or return different types.
class Calculator {
add(a: number, b: number): number;
add(a: string, b: string): string;
add(a: any, b: any): any {
return a + b;
}
}
const calc = new Calculator();
console.log(calc.add(2, 3)); // Output: 5
console.log(calc.add("Hello", " World")); // Output: Hello World
In this example:
- The
add
method is overloaded to accept either twonumber
parameters or twostring
parameters.
Static Properties and Methods
Static properties and methods belong to the class itself rather than an instance of the class. These can be accessed using the class name directly.
class Counter {
static count: number = 0;
static increment(): void {
Counter.count++;
}
static getCount(): number {
return Counter.count;
}
}
Counter.increment();
console.log(Counter.getCount()); // Output: 1
In this example:
- The static property
count
is accessed directly on the class usingCounter.count
. - The static method
increment
modifies the static propertycount
.
Access Modifiers
TypeScript supports access modifiers for both properties and methods to control the visibility and accessibility of class members:
public
: Accessible from anywhere (default modifier).private
: Accessible only within the class.protected
: Accessible within the class and subclasses.
class Person {
public name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public getAge(): number {
return this.age;
}
}
const person = new Person("Alice", 30);
console.log(person.name); // Output: Alice
console.log(person.getAge()); // Output: 30
// console.log(person.age); // Error: Property 'age' is private and only accessible within class 'Person'.
In this example:
name
ispublic
, so it can be accessed directly.age
isprivate
, so it cannot be accessed directly outside the class.
Summary
In TypeScript, properties and methods define the structure and behavior of a class. Properties hold data, while methods define actions on that data. TypeScript enhances object-oriented programming with static typing, optional properties, access modifiers, and method overloading. Understanding these concepts is crucial for building robust and maintainable TypeScript applications.