Class

Classes may have properties, methods, and constructors.

class Vehicle { }

Properties

class Person {
    first_name: string;
    last_name: string;
    age: number;
}

Methods

class Person {
    first_name: string;
    last_name: string;
    age: number;

    greet() {
        console.log("Hello", this.first_name);
    }
}

var p: Person;
p = new Person();
p.first_name = 'Felipe';
p.greet();
class Person {
    ageInYears(years: number): number {
        return this.age + years;
    }
}

var p: Person = new Person();
p.age = 6;
p.ageInYears(12);

Constructors

A constructor is a special method that is executed when a new instance of the class is being created.

Constructor methods must be named constructor

When a class has no constructor defined explicitly one will be created automatically:

class Vehicle {}

// same as
class Vehicle {
    constructor() {}
}
// #1
class Person{
    first_name: string;
    last_name: string;
    age: number;

    constructor(first_name: string, last_name: string, age: number) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.age = age;
     }
}
var p: Person = new Person('Felipe', 'Coury', 36);
p.greet();

// #2 - same as above
class Person{    
    constructor(public first_name: string,public last_name: string, public age: number) { }
}
var p: Person = new Person('Felipe', 'Coury', 36);
p.greet();

Inheritance

class Report {
    data: Array<string>;

    constructor(mydata: Array<string>) {
        this.data = mydata;
    }

    run() {
        this.data.forEach(function (line) { console.log(line); });
    }
}

var r: Report = new Report(['First line', 'Second line']);
r.run();

// output
First line
Second line

Let's add header to report

class TabbedReport extends Report {
    headers: Array<string>;

    constructor(headers: string[], values: string[]) {
        super(values); // shuld be 1st in constructor
        this.headers = headers;
    }

    run() {
        console.log(headers);
        super.run();
    }
}    

var headers: string[] = ['Name'];
var data: string[] = ['Hemant', 'Vinay', 'Varun'];
var r: TabbedReport = new TabbedReport(headers, data)
r.run();

// output
["Name"]
Hemant
Vinay
Varun

Last updated

Was this helpful?