Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Ts Classes in TypeScript

Ts Classes in TypeScript

Classes in TypeScript provide a way to create reusable, object-oriented code. They bring the structure of traditional object-oriented programming (OOP) to JavaScript with features like inheritance, encapsulation, and abstraction.


Defining a Class

Here’s a basic example:

typescript

const person = new Person("Alice", 30);person.greet(); // "Hello, my name is Alice and I am 30 years old."


Key Features of TypeScript Classes

1. Class Properties

  • Properties can be explicitly defined with types.
  • Default values can be assigned.

typescript

class Product { name: string = "Default Product"; price: number = 0;}

2. Constructor

  • A special method used to initialize object properties.

typescript

class Car { make: string; model: string; constructor(make: string, model: string) { class Animal { public species: string; private weight: number; constructor(species: string, weight: number) { console.log(tiger.getWeight()); // 200

4. Readonly Properties

Properties that can only be set during initialization.

typescript

class Book { readonly title: string; constructor(title: string) { class MathUtils { static PI: number = 3.14; static calculateCircumference(radius: number): number { return 2 * MathUtils.PI * radius; }}console.log(MathUtils.calculateCircumference(5)); // 31.4


Inheritance

Classes can inherit from other classes using the extends keyword.

typescript

class Employee { name: string; constructor(name: string) { abstract class Shape { abstract getArea(): number; describe(): void { console.log("This is a shape."); }}class Circle extends Shape { radius: number; constructor(radius: number) { interface Flyable { fly(): void;}class Bird implements Flyable { fly(): void { console.log("The bird is flying."); }}


Class Example: Real-World Use Case

A Simple Banking System:

typescript

class BankAccount { private balance: number; constructor(private accountHolder: string, initialBalance: number) { class Point { constructor(public x: number, public y: number) {}}class User { constructor(public name: string, public age?: number) {}}const user = new User("Alice");console.log(user.age); // undefined

  • Index Signatures
    Allow defining dynamic properties.

    typescript

    class Dictionary { [key: string]: string;}const dict = new Dictionary();dict["hello"] = "world";

  • Disclaimer for AI-Generated Content:
    The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
    html
    docker
    php
    kubernetes
    golang
    mysql
    postgresql
    mariaDB
    sql