Class and objects in Typescript

Class and objects in Typescript

1) Create a project in typescript with this structure

run this command

npx webpack-cli init

image.png

2) Create a class

export class class1{

}

3) Add a members

export class class1{        
    constructor(){
        console.log("class1");
    }
    private _balance : number = 0;
    //methods for _balance
    getBalance(){
        return this._balance;
    }
    setBalance(balance : number){
        this._balance = balance;
    }
    //methods for deposit balance
    deposit(amount : number){
        this._balance += amount;
    }
    //method for withdraw balance
    withdraw(amount : number){
        this._balance -= amount;
    }
}

4) in our file "index.ts" we instantiate the class "class1"

import { class1 } from './scripts/class1';

//instantiate class1
const class1Instance = new class1();

// call method deposit on class1Instance
class1Instance.deposit(100);
class1Instance.deposit(150); //250
class1Instance.withdraw(75); //175

// get balance of class1Instance
const balance = class1Instance.getBalance();

console.log("Balance: " + balance);

5) run the project

npm run serve

6) we see in the console the values that we have added to the object that we instantiate of class 1

// call method deposit on class1Instance
class1Instance.deposit(100);
class1Instance.deposit(150); //250
class1Instance.withdraw(75); //175

image.png

Blue Nerd Gaming Sport and Esport Logo.png