Happylab Logo
Published on

Day26: TypeScript Learning : TypeScript and ES6 Classes

Authors

Day26: TypeScript Learning : TypeScript and ES6 Classes

In this article, we will explore how TypeScript enhances the use of ES6 classes, including class properties, methods, and inheritance.

If there are any mistakes, please feel free to leave comments. Thank you!


Class Properties

In TypeScript, you can define properties directly in the class. For example:

class Person {
    name: string;
    age: number;

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

const person = new Person("John", 30);
console.log(person.name); // John

Class Methods

You can also define methods within a class:

class Person {
    name: string;
    age: number;

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

    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
}

const person = new Person("John", 30);
person.greet(); // Hello, my name is John

Inheritance

TypeScript supports class inheritance, allowing you to create subclasses:

class Employee extends Person {
    employeeId: number;

    constructor(name: string, age: number, employeeId: number) {
        super(name, age);
        this.employeeId = employeeId;
    }

    displayId() {
        console.log(`Employee ID: ${this.employeeId}`);
    }
}

const employee = new Employee("Jane", 28, 123);
employee.greet(); // Hello, my name is Jane
employee.displayId(); // Employee ID: 123

Thank you for reading! See you tomorrow!


References

https://www.typescriptlang.org/docs/handbook/2/classes.html