HomeToolsAbout

Class

Basics

// Define a class with properties and methods class MyClass { // define properties private privateField: string; public publicField: number; // Constructor to initialize the class constructor(privateField: string, publicField: number) { this.privateField = privateField; this.publicField = publicField; } // define methods // Method with parameters and return type public calculateSum(x: number, y: number): number { return x + y; } // Getter method getPrivateField(): string { return this.privateField; } } // Create an instance of the class const myInstance = new MyClass("PrivateValue", 42); // Access fields and methods console.log(myInstance.publicField); // Output: 42 console.log(myInstance.calculateSum(5, 3)); // Output: 8 console.log(myInstance.getPrivateField()); // Output: PrivateValue

Properties

In TS, each member is public by default

Private Properties

Private properties get create by using a # prefix and cannot be legally referenced outside of the class

private Keyword

private keyword is a compile time annotation

  • Compiler understands that the property should only be accessible inside that class
  • private keyword is not enforced at runtime
  • JS code emitted after compiling is a regular field and not a # private field in JS

Private Methods

Private methods cannot be defined directly in an interface as interfaces are meant to declare the public contract of a class

Getters, Setters, and Generators

class Rectangle { constructor(height, width) { this.height = height; this.width = width; } // Define Getter get area() { return this.calcArea(); } // Define method calcArea() { return this.height * this.width; } // generators "yield" results // has its own state to track the call count to "yield" different results *getSides() { yield this.height; yield this.width; yield this.height; yield this.width; } } const square = new Rectangle(10, 10); console.log(square.area); // 100 console.log([...square.getSides()]); // [10, 10, 10, 10]
AboutContact