Better Programming

Advice for programmers.

Follow publication

Member-only story

Static Properties, Abstract Classes, and Constructor Functions in TypeScript

John Au-Yeung
Better Programming
Published in
6 min readFeb 3, 2020

Photo by Christina @ wocintechchat.com on Unsplash

Classes in TypeScript, as in JavaScript, are a special syntax for its prototypical inheritance model that’s a comparable inheritance in class-based object oriented languages. Classes are just special functions added to ES6 that are meant to mimic the class keyword from these other languages.

In JavaScript, we can have class declarations and class expressions because they’re just functions. So like all other functions, there are function declarations and function expressions. This is the same with TypeScript. Classes serve as templates to create new objects. TypeScript extends the syntax of classes of JavaScript and then adds its own twist to it. In this piece, we’ll look at static properties, abstract classes, and constructor functions.

Static Properties

With TypeScript, we can designate members as instance variables, which don’t have the keyword static before them, and static members, which have the keyword static keyword before them.

Static members can be accessed without having the class instantiated. Of course, this is given to the access modifiers that are designated for the member. So public static members can be accessed directly from outside the class. Private static members can only be used within the class, and protected members can be accessed by a class the member is defined in and also by subclasses of that class.

The static keyword can be used by both fields and methods. For example, we can use it like in the following code:

class Person {
static numPeople = 0;
constructor(name: string) {
Person.numPeople++;
}
static getNumPeople() {
return this.numPeople;
}
}
const john = new Person('John');
const jane = new Person('Jane');
console.log(Person.numPeople);
console.log(Person.getNumPeople());

In the code above, every time we instantiate the Person class, we increase the static property numPeople by one. Since static properties are shared by all instances of the class and don’t belong to any one instance, we can access numPeople directly by using Person.numPeople.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

Write a response