TypeScript Classes


TypeScript classes are blueprints of objects and can be very powerful. They are similar to interfaces. Classes are meant to be constructed. When you construct an instance of a class you are using the class to create an object that consumes computer memory.

Here is what the website www.typescriptlang.org says about classes: “Traditional JavaScript uses functions and prototype-based inheritance to build up reusable components, but this may feel a bit awkward to programmers more comfortable with an object-oriented approach, where classes inherit functionality and objects are built from these classes. Starting with ECMAScript 2015, also known as ECMAScript 6, JavaScript programmers will be able to build their applications using this object-oriented class-based approach. In TypeScript, we allow developers to use these techniques now, and compile them down to JavaScript that works across all major browsers and platforms, without having to wait for the next version of JavaScript”.

Shown below is some example TypeScript code and its compiled JavaScript code.

class.ts

class Stark {
  name: string;
}
// create an object of type Stark named ned
var ned = new Stark();

class.js

var Stark = (function () {
    function Stark() {
    }
    return Stark;
}());
// create an object of type Stark named ned
var ned = new Stark();

Properties in a class cannot be declared optional as they can be in interfaces. However, classes can implement interfaces that have optional properties.

Constructors

Classes can have constructor properties which are functions that run automatically when an object is instantiated.

Static Properties in your Class

Consider the following code. We have not instantiated the class (using the new keyword) but still we have access to the castle property’s value “Winterfell”.

class Stark {
    name: string = "Duke";
    static castle: string = "Winterfell"
    saying: string;
}
console.log(Stark.castle);
//DOES NOT COMPILE: console.log(Stark.name);

Methods

Classes can have methods.

class Stark {
    name: string = "Duke";
    static castle: string = "Winterfell"
    saying: string;

    constructor(){
      this.saying = Stark.castle;
    }

    hello(person: string){  // methods are functions
      console.log("Hello, " + person + "! How are you?");
    }
}
// create an object of type Stark named ned
var ned = new Stark();
ned.saying = "Winter is here";
ned.hello("Linda");  // call the method
Series Navigation<< TypeScript Interfaces Part 2TypeScript Inheritance >>

Leave a comment

Your email address will not be published. Required fields are marked *