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 can 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.

Classes

Let’s take a look at a simple class-based example:

  1. class Greeter {
  2. greeting: string;
  3. constructor(message: string) {
  4. this.greeting = message;
  5. }
  6. greet() {
  7. return "Hello, " + this.greeting;
  8. }
  9. }
  10. let greeter = new Greeter("world");Try

The syntax should look familiar if you’ve used C# or Java before. We declare a new class Greeter. This class has three members: a property called greeting, a constructor, and a method greet.

You’ll notice that in the class when we refer to one of the members of the class we prepend this.. This denotes that it’s a member access.

In the last line we construct an instance of the Greeter class using new. This calls into the constructor we defined earlier, creating a new object with the Greeter shape, and running the constructor to initialize it.

Inheritance

In TypeScript, we can use common object-oriented patterns. One of the most fundamental patterns in class-based programming is being able to extend existing classes to create new ones using inheritance.

Let’s take a look at an example:

  1. class Animal {
  2. move(distanceInMeters: number = 0) {
  3. console.log(`Animal moved ${distanceInMeters}m.`);
  4. }
  5. }
  6. class Dog extends Animal {
  7. bark() {
  8. console.log("Woof! Woof!");
  9. }
  10. }
  11. const dog = new Dog();
  12. dog.bark();
  13. dog.move(10);
  14. dog.bark();Try

This example shows the most basic inheritance feature: classes inherit properties and methods from base classes. Here, Dog is a derived class that derives from the Animal base class using the extends keyword. Derived classes are often called subclasses, and base classes are often called superclasses.

Because Dog extends the functionality from Animal, we were able to create an instance of Dog that could both bark() and move().

Let’s now look at a more complex example.

  1. class Animal {
  2. name: string;
  3. constructor(theName: string) {
  4. this.name = theName;
  5. }
  6. move(distanceInMeters: number = 0) {
  7. console.log(`${this.name} moved ${distanceInMeters}m.`);
  8. }
  9. }
  10. class Snake extends Animal {
  11. constructor(name: string) {
  12. super(name);
  13. }
  14. move(distanceInMeters = 5) {
  15. console.log("Slithering...");
  16. super.move(distanceInMeters);
  17. }
  18. }
  19. class Horse extends Animal {
  20. constructor(name: string) {
  21. super(name);
  22. }
  23. move(distanceInMeters = 45) {
  24. console.log("Galloping...");
  25. super.move(distanceInMeters);
  26. }
  27. }
  28. let sam = new Snake("Sammy the Python");
  29. let tom: Animal = new Horse("Tommy the Palomino");
  30. sam.move();
  31. tom.move(34);Try

This example covers a few other features we didn’t previously mention. Again, we see the extends keywords used to create two new subclasses of Animal: Horse and Snake.

One difference from the prior example is that each derived class that contains a constructor function must call super() which will execute the constructor of the base class. What’s more, before we ever access a property on this in a constructor body, we have to call super(). This is an important rule that TypeScript will enforce.

The example also shows how to override methods in the base class with methods that are specialized for the subclass. Here both Snake and Horse create a move method that overrides the move from Animal, giving it functionality specific to each class. Note that even though tom is declared as an Animal, since its value is a Horse, calling tom.move(34) will call the overriding method in Horse:

  1. Slithering...
  2. Sammy the Python moved 5m.
  3. Galloping...
  4. Tommy the Palomino moved 34m.

Public, private, and protected modifiers

Public by default

In our examples, we’ve been able to freely access the members that we declared throughout our programs. If you’re familiar with classes in other languages, you may have noticed in the above examples we haven’t had to use the word public to accomplish this; for instance, C# requires that each member be explicitly labeled public to be visible. In TypeScript, each member is public by default.

You may still mark a member public explicitly. We could have written the Animal class from the previous section in the following way:

  1. class Animal {
  2. public name: string;
  3. public constructor(theName: string) {
  4. this.name = theName;
  5. }
  6. public move(distanceInMeters: number) {
  7. console.log(`${this.name} moved ${distanceInMeters}m.`);
  8. }
  9. }Try

ECMAScript Private Fields

With TypeScript 3.8, TypeScript supports the new JavaScript syntax for private fields:

  1. class Animal {
  2. #name: string;
  3. constructor(theName: string) {
  4. this.#name = theName;
  5. }
  6. }
  7. new Animal("Cat").#name;
  8. Property '#name' is not accessible outside class 'Animal' because it has a private identifier.18013Property '#name' is not accessible outside class 'Animal' because it has a private identifier.Try

This syntax is built into the JavaScript runtime and can have better guarantees about the isolation of each private field. Right now, the best documentation for these private fields is in the TypeScript 3.8 release notes.

Understanding TypeScript’s private

TypeScript also has its own way to declare a member as being marked private, it cannot be accessed from outside of its containing class. For example:

  1. class Animal {
  2. private name: string;
  3. constructor(theName: string) {
  4. this.name = theName;
  5. }
  6. }
  7. new Animal("Cat").name;
  8. Property 'name' is private and only accessible within class 'Animal'.2341Property 'name' is private and only accessible within class 'Animal'.Try

TypeScript is a structural type system. When we compare two different types, regardless of where they came from, if the types of all members are compatible, then we say the types themselves are compatible.

However, when comparing types that have private and protected members, we treat these types differently. For two types to be considered compatible, if one of them has a private member, then the other must have a private member that originated in the same declaration. The same applies to protected members.

Let’s look at an example to better see how this plays out in practice:

  1. class Animal {
  2. private name: string;
  3. constructor(theName: string) {
  4. this.name = theName;
  5. }
  6. }
  7. class Rhino extends Animal {
  8. constructor() {
  9. super("Rhino");
  10. }
  11. }
  12. class Employee {
  13. private name: string;
  14. constructor(theName: string) {
  15. this.name = theName;
  16. }
  17. }
  18. let animal = new Animal("Goat");
  19. let rhino = new Rhino();
  20. let employee = new Employee("Bob");
  21. animal = rhino;
  22. animal = employee;
  23. Type 'Employee' is not assignable to type 'Animal'.
  24. Types have separate declarations of a private property 'name'.2322Type 'Employee' is not assignable to type 'Animal'.
  25. Types have separate declarations of a private property 'name'.Try

In this example, we have an Animal and a Rhino, with Rhino being a subclass of Animal. We also have a new class Employee that looks identical to Animal in terms of shape. We create some instances of these classes and then try to assign them to each other to see what will happen. Because Animal and Rhino share the private side of their shape from the same declaration of private name: string in Animal, they are compatible. However, this is not the case for Employee. When we try to assign from an Employee to Animal we get an error that these types are not compatible. Even though Employee also has a private member called name, it’s not the one we declared in Animal.

Understanding protected

The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed within deriving classes. For example,

  1. class Person {
  2. protected name: string;
  3. constructor(name: string) {
  4. this.name = name;
  5. }
  6. }
  7. class Employee extends Person {
  8. private department: string;
  9. constructor(name: string, department: string) {
  10. super(name);
  11. this.department = department;
  12. }
  13. public getElevatorPitch() {
  14. return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  15. }
  16. }
  17. let howard = new Employee("Howard", "Sales");
  18. console.log(howard.getElevatorPitch());
  19. console.log(howard.name);
  20. Property 'name' is protected and only accessible within class 'Person' and its subclasses.2445Property 'name' is protected and only accessible within class 'Person' and its subclasses.Try

Notice that while we can’t use name from outside of Person, we can still use it from within an instance method of Employee because Employee derives from Person.

A constructor may also be marked protected. This means that the class cannot be instantiated outside of its containing class, but can be extended. For example,

  1. class Person {
  2. protected name: string;
  3. protected constructor(theName: string) {
  4. this.name = theName;
  5. }
  6. }
  7. // Employee can extend Person
  8. class Employee extends Person {
  9. private department: string;
  10. constructor(name: string, department: string) {
  11. super(name);
  12. this.department = department;
  13. }
  14. public getElevatorPitch() {
  15. return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  16. }
  17. }
  18. let howard = new Employee("Howard", "Sales");
  19. let john = new Person("John");
  20. Constructor of class 'Person' is protected and only accessible within the class declaration.2674Constructor of class 'Person' is protected and only accessible within the class declaration.Try

Readonly modifier

You can make properties readonly by using the readonly keyword. Readonly properties must be initialized at their declaration or in the constructor.

  1. class Octopus {
  2. readonly name: string;
  3. readonly numberOfLegs: number = 8;
  4. constructor(theName: string) {
  5. this.name = theName;
  6. }
  7. }
  8. let dad = new Octopus("Man with the 8 strong legs");
  9. dad.name = "Man with the 3-piece suit";
  10. Cannot assign to 'name' because it is a read-only property.2540Cannot assign to 'name' because it is a read-only property.Try

Parameter properties

In our last example, we had to declare a readonly member name and a constructor parameter theName in the Octopus class. This is needed in order to have the value of theName accessible after the Octopus constructor is executed. Parameter properties let you create and initialize a member in one place. Here’s a further revision of the previous Octopus class using a parameter property:

  1. class Octopus {
  2. readonly numberOfLegs: number = 8;
  3. constructor(readonly name: string) {}
  4. }
  5. let dad = new Octopus("Man with the 8 strong legs");
  6. dad.name;Try

Notice how we dropped theName altogether and just use the shortened readonly name: string parameter on the constructor to create and initialize the name member. We’ve consolidated the declarations and assignment into one location.

Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly, or both. Using private for a parameter property declares and initializes a private member; likewise, the same is done for public, protected, and readonly.

Accessors

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.

Let’s convert a simple class to use get and set. First, let’s start with an example without getters and setters.

  1. class Employee {
  2. fullName: string;
  3. }
  4. let employee = new Employee();
  5. employee.fullName = "Bob Smith";
  6. if (employee.fullName) {
  7. console.log(employee.fullName);
  8. }Try

While allowing people to randomly set fullName directly is pretty handy, we may also want enforce some constraints when fullName is set.

In this version, we add a setter that checks the length of the newName to make sure it’s compatible with the max-length of our backing database field. If it isn’t we throw an error notifying client code that something went wrong.

To preserve existing functionality, we also add a simple getter that retrieves fullName unmodified.

  1. const fullNameMaxLength = 10;
  2. class Employee {
  3. private _fullName: string;
  4. get fullName(): string {
  5. return this._fullName;
  6. }
  7. set fullName(newName: string) {
  8. if (newName && newName.length > fullNameMaxLength) {
  9. throw new Error("fullName has a max length of " + fullNameMaxLength);
  10. }
  11. this._fullName = newName;
  12. }
  13. }
  14. let employee = new Employee();
  15. employee.fullName = "Bob Smith";
  16. if (employee.fullName) {
  17. console.log(employee.fullName);
  18. }Try

To prove to ourselves that our accessor is now checking the length of values, we can attempt to assign a name longer than 10 characters and verify that we get an error.

A couple of things to note about accessors:

First, accessors require you to set the compiler to output ECMAScript 5 or higher. Downleveling to ECMAScript 3 is not supported. Second, accessors with a get and no set are automatically inferred to be readonly. This is helpful when generating a .d.ts file from your code, because users of your property can see that they can’t change it.

Static Properties

Up to this point, we’ve only talked about the instance members of the class, those that show up on the object when it’s instantiated. We can also create static members of a class, those that are visible on the class itself rather than on the instances. In this example, we use static on the origin, as it’s a general value for all grids. Each instance accesses this value through prepending the name of the class. Similarly to prepending this. in front of instance accesses, here we prepend Grid. in front of static accesses.

  1. class Grid {
  2. static origin = { x: 0, y: 0 };
  3. calculateDistanceFromOrigin(point: { x: number; y: number }) {
  4. let xDist = point.x - Grid.origin.x;
  5. let yDist = point.y - Grid.origin.y;
  6. return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
  7. }
  8. constructor(public scale: number) {}
  9. }
  10. let grid1 = new Grid(1.0); // 1x scale
  11. let grid2 = new Grid(5.0); // 5x scale
  12. console.log(grid1.calculateDistanceFromOrigin({ x: 10, y: 10 }));
  13. console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 }));Try

Abstract Classes

Abstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members. The abstract keyword is used to define abstract classes as well as abstract methods within an abstract class.

  1. abstract class Animal {
  2. abstract makeSound(): void;
  3. move(): void {
  4. console.log("roaming the earth...");
  5. }
  6. }Try

Methods within an abstract class that are marked as abstract do not contain an implementation and must be implemented in derived classes. Abstract methods share a similar syntax to interface methods. Both define the signature of a method without including a method body. However, abstract methods must include the abstract keyword and may optionally include access modifiers.

  1. abstract class Department {
  2. constructor(public name: string) {}
  3. printName(): void {
  4. console.log("Department name: " + this.name);
  5. }
  6. abstract printMeeting(): void; // must be implemented in derived classes
  7. }
  8. class AccountingDepartment extends Department {
  9. constructor() {
  10. super("Accounting and Auditing"); // constructors in derived classes must call super()
  11. }
  12. printMeeting(): void {
  13. console.log("The Accounting Department meets each Monday at 10am.");
  14. }
  15. generateReports(): void {
  16. console.log("Generating accounting reports...");
  17. }
  18. }
  19. let department: Department; // ok to create a reference to an abstract type
  20. department = new Department(); // error: cannot create an instance of an abstract class
  21. Cannot create an instance of an abstract class.2511Cannot create an instance of an abstract class.department = new AccountingDepartment(); // ok to create and assign a non-abstract subclass
  22. department.printName();
  23. department.printMeeting();
  24. department.generateReports();
  25. Property 'generateReports' does not exist on type 'Department'.2339Property 'generateReports' does not exist on type 'Department'.Try

Advanced Techniques

Constructor functions

When you declare a class in TypeScript, you are actually creating multiple declarations at the same time. The first is the type of the instance of the class.

  1. class Greeter {
  2. greeting: string;
  3. constructor(message: string) {
  4. this.greeting = message;
  5. }
  6. greet() {
  7. return "Hello, " + this.greeting;
  8. }
  9. }
  10. let greeter: Greeter;
  11. greeter = new Greeter("world");
  12. console.log(greeter.greet()); // "Hello, world"Try

Here, when we say let greeter: Greeter, we’re using Greeter as the type of instances of the class Greeter. This is almost second nature to programmers from other object-oriented languages.

We’re also creating another value that we call the constructor function. This is the function that is called when we new up instances of the class. To see what this looks like in practice, let’s take a look at the JavaScript created by the above example:

  1. let Greeter = (function () {
  2. function Greeter(message) {
  3. this.greeting = message;
  4. }
  5. Greeter.prototype.greet = function () {
  6. return "Hello, " + this.greeting;
  7. };
  8. return Greeter;
  9. })();
  10. let greeter;
  11. greeter = new Greeter("world");
  12. console.log(greeter.greet()); // "Hello, world"Try

Here, let Greeter is going to be assigned the constructor function. When we call new and run this function, we get an instance of the class. The constructor function also contains all of the static members of the class. Another way to think of each class is that there is an instance side and a static side.

Let’s modify the example a bit to show this difference:

  1. class Greeter {
  2. static standardGreeting = "Hello, there";
  3. greeting: string;
  4. greet() {
  5. if (this.greeting) {
  6. return "Hello, " + this.greeting;
  7. } else {
  8. return Greeter.standardGreeting;
  9. }
  10. }
  11. }
  12. let greeter1: Greeter;
  13. greeter1 = new Greeter();
  14. console.log(greeter1.greet()); // "Hello, there"
  15. let greeterMaker: typeof Greeter = Greeter;
  16. greeterMaker.standardGreeting = "Hey there!";
  17. let greeter2: Greeter = new greeterMaker();
  18. console.log(greeter2.greet()); // "Hey there!"Try

In this example, greeter1 works similarly to before. We instantiate the Greeter class, and use this object. This we have seen before.

Next, we then use the class directly. Here we create a new variable called greeterMaker. This variable will hold the class itself, or said another way its constructor function. Here we use typeof Greeter, that is “give me the type of the Greeter class itself” rather than the instance type. Or, more precisely, “give me the type of the symbol called Greeter,” which is the type of the constructor function. This type will contain all of the static members of Greeter along with the constructor that creates instances of the Greeter class. We show this by using new on greeterMaker, creating new instances of Greeter and invoking them as before.

Using a class as an interface

As we said in the previous section, a class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, you can use them in the same places you would be able to use interfaces.

  1. class Point {
  2. x: number;
  3. y: number;
  4. }
  5. interface Point3d extends Point {
  6. z: number;
  7. }
  8. let point3d: Point3d = { x: 1, y: 2, z: 3 };Try