This section and the namespace section below will show how TypeScript emits consistent, idiomatic JavaScript when emitting ECMAScript 3 or 5 compliant code for classes and namespaces. The goal of TypeScript’s translation is to emit exactly what a programmer would type when implementing a class or namespace unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We’ll start with a simple BankAccount class.

    This class generates the following JavaScript code.

    1. function BankAccount() {
    2. this.balance = 0;
    3. }
    4. BankAccount.prototype.deposit = function(credit) {
    5. };
    6. return BankAccount;
    7. })();

    This TypeScript class declaration creates a variable named ‘BankAccount’ whose value is the constructor function for ‘BankAccount’ instances. This declaration also creates an instance type of the same name. If we were to write this type as an interface it would look like the following.

    1. var BankAccount: new() => BankAccount;

    The function signature is prefixed with the keyword ‘new’ indicating that the ‘BankAccount’ function must be called as a constructor. It is possible for a function’s type to have both call and constructor signatures. For example, the type of the built-in JavaScript Date object includes both kinds of signatures.

    If we want to start our bank account with an initial balance, we can add to the ‘BankAccount’ class a constructor declaration.

    This version of the ‘BankAccount’ class requires us to introduce a constructor parameter and then assign it to the ‘balance’ field. To simplify this common case, TypeScript accepts the following shorthand syntax.

    1. }
    2. deposit(credit: number) {
    3. this.balance += credit;
    4. return this.balance;

    TypeScript classes also support inheritance, as in the following example.

    In this example, the class ‘CheckingAccount’ derives from class ‘BankAccount’. The constructor for ‘CheckingAccount’ calls the constructor for class ‘BankAccount’ using the ‘super’ keyword. In the emitted JavaScript code, the prototype of ‘CheckingAccount’ will chain to the prototype of ‘BankAccount’.

    TypeScript classes may also specify static members. Static class members become properties of the class constructor.