Intro









Inheritance

Just like Interfaces, classes can be extended by other classes, creating an inheritance chain. This behaves just a little differently than interfaces, though, since we have to account for the constructor function. Lets create the same class inheritance that we did earlier with Interfaces and adjust it for our class.


Static Properties

We can assign static properties to a class. These are properties which only exist on the class definition, not class instances. We do this by appending the **static**keyword in front of the property name.


Annotating Class Constructors

For our **Vegetable** class, the type that it represents is for the class instance that is created when we instantiate it. What if we wanted to have an annotation for the class constructor function? For example, suppose we had a function that we pass a class constructor to. It instantiates the class, and then does something with it.

Remember how **typeof Vegetable** or any other class represents the constructor function. We can use that to get the construct signature for this particular class. The inferred type from this will also give us a hint of how we can write a construct signature on our own.

This looks just like a regular function annotation, except it uses the **new** keyword to indicate that it's creating a class instance - that's what makes it a construct signature.

Remember, though, that our class has some static properties which should be present on the constructor function. For that, we have to create a separate type that includes a callable interface for the constructor.

If we wanted to make this class construct signature work with more than just **Vegetable** classes, we could turn it into a generic interface, where the generic type is the class instance.



Abstract Classes

Abstract classes are classes which cannot be instantiated, but provide implementation details for any classes which extend them. This differs from Interfaces, which only provide type definitions. You can think of them as being blueprints, or templates, which have to be followed when creating certain types of class definitions. They only exist in TypeScript, so you can't use an abstract class when you are writing JavaScript.

Abstract classes can include abstract methods, which include a function type signature, but contain no implementation. Abstract methods must be implemented by the derived class; if the derived class doesn't implement every abstract method, TypeScript will throw an error.

Copyright 2023 © Borja Leiva

Made within London