TypeScript Classes and Interfaces

Learn via video courses
Topics Covered

Overview

Interfaces and Classes are the elemental parts of object-oriented programming. TypeScript is an object-oriented programming language, from ES6 and later, that supports OOPS features like interfaces, classes, encapsulation, etc. They are powerful structures that facilitate not just object-oriented but also type-checking in TypeScript. If we want to create and pass a typed-checked class object, we should use Classes. If we need to work without creating objects, then we should use Interfaces.

Introduction

TypeScript provides an additional syntax for type checking and converts the code to clean JavaScript that runs on any browser. Classes are involved in all stages of code. After the conversion of the TS code to a JS file, we can find them in all the files. The interface is an abstract data type that tells the compiler which property names a given object should have. TypeScript creates implicit interfaces once you define an object with properties. We can create optional properties and read-only properties with Interfaces.

What is a Class in TypeScript?

A class is considered a blueprint or template by which we can create objects with specific properties and methods. It is used to create reusable components. A class includes properties, methods, and constructors. We can declare an object with the new keyword in a class. The `super keyword is used to make a call to the parent constructor and passes its property values.

Why do you need Classes:

We need classes in TypeScript when:

  • We need to write the logic that is responsible for giving functionality to our app.
  • We need to link behavior with the data more closely.

Properties in a Class Definition

Following are the properties that we specify in a class definition:

  • Fields - It is the variable that we declare in a class.
  • Methods - It represents an action for the object.
  • Constructor - It is responsible for assigning the object in the memory.
  • Nested class and Interface - This means that a class can contain another class.

Creating a Class

We can create a class and add fields, properties, functions, and constructors.

Syntax

This example creates a Person class that will have a constructor that accepts a single parameter name that initializes the instance property with the same name.

When to Use Classes in TypeScript?

There are some cases where we have to use classes in TypeScript:

Case1: Class is a factory of objects. A factory is a place where all related data and functions to one object or material are grouped in one place so that our flexibility in our work code and other work that is not related doesn't interact and cause any disturbance. In such a case, we should use classes when we need flexibility` in complex code without disturbance.

Example

Output

Case2: Class provides support for object-oriented programming, so it makes our code more usable, maintainable, and scalable. This helps in handling large code bases with efficiency. Hence, when we need to handle large code and want these functions of classes, we use classes.

Example

Output

Functions

We can create a function on an instance member of a class, on the prototype, or as a static function. We want to use the prototype for function on classes if we intend to create multiple instances of the object. As the prototype can save some memory as it exists only once while creating a function on every instance of the class would create 1 function per instance.

Example

If we want to create a function as an instance member:

Inheritance

Inheritance is a property in which a class can reuse its properties and methods of another class. The class which inherits properties and methods is known as a child class. And the class whose properties and methods are inherited is known as a parent class. It allows you to reuse the functionality of an existing class without rewriting it. We use the extends keyword to inherit a class.

Example

Output

In the above example, the BMW class extends the Car class by using the extends keyword. The BMW class will have all the members of the Car class. The constructor of the BMW class declares its members as well as the parent class's properties by using the keyword super. This keyword is used to call the parent constructor and its values.

What is an Interface in TypeScript?

The interface is a virtual structure that is used for type-checking. We use the interface keyword to create a new interface with some identity. It is a structure that defines the properties and methods for objects with names and types. It contains only the declaration of methods and fields, but not the implementation. A class can inherit an interface, and the class that implements an interface defines all its members. The interface is used to pass the object as parameters, and validate the specific structure of properties.

When Do We Use Interface in TypeScript?

We use an interface in TypeScript to validate a structure of an object when we are creating an object and passing objects as parameters. The interface is available only in TypeScript code when it compiles JavaScript code, its existence disappears and doesn't make the final source code heavier. We use an interface in our code when we want type checking but the code should not be bulky.

Example for Declaring Interfaces:

Output

Interface as Type

In TypeScript, interfaces are used to define a type and implement it in the class.

Example for Interface as Type

In the above example, the interface Value has two properties key and value. A variable val1 has been declared as a Value type. So, it should follow the same structure as Value. This means only an object with properties key of number type and value of string type should be assigned to a variable val1. The compiler will throw an error if there occurs a change in the name of the properties or data type is different than Value. Another variable declared is val2 is also declared as a Valuetype but the assigned value is v instead of value, So this will throw an error. In the same manner, val3 assigns a number to the value property, hence, the compiler will throw a compilation error.

Interface as Function Type

A function is a piece of code that executes some specific task. It is used to implement object-oriented programming concepts like Classes, Objects, Polymorphism, and Abstraction. It is used to ensure the reusability and maintainability of the code.

Structure:

Following is the structure of an interface with a function type:

A function type has two parts: parameters and return type. When we declare a function type, we have to specify both parts with the following syntax:

Here is an example that shows how to declare which has a function type that accepts two numbers and returns a number:

The function type accepts two arguments: x and y with the type number. The type of return value is number that follows the fat arrow => appeared between parameters and return type.

Once assigning a variable with a function type, we can assign the function with the same type to the variable. TypeScript compiler will check the number of parameters along with their types and return type.

Here is an example to show how we can assign a function to a specific variable.

Also, we can declare a variable and pass a function to a variable.

If we assign other functions whose type doesn't match the mul variable, the TypeScript compiler will throw an error:

In the above-given example, we reassigned a function whose type doesn't match the mul function variable.

Inferring function types:

TypeScript compiler can interpret the function type when you have the type on one side of the equation. This form of type inference is known as contextual typing.

Inferring function types

In the above example, the add function will take the type (x: number, y: number) => number. Developers can reduce the amount of code with annotations by using type inference. Takeaway:

Classes support the concept of method overriding and inheritance. Also, it provides support for member visibility. Interfaces are loosely-coupled and provide support for multiple inheritances.

Interface Vs Classes

There are differences between Interfaces and Classes. Some of them are:

InterfacesClasses
We will declare an interface using the interface keyword.We will declare a class using the class keyword.
An interface cannot be incorporated further.A class can be incorporated to create an object.
During the compilation of code, an interface is completely disappeared.During the compilation of code, a class doesn't disappear.
An interface cannot have a constructor.A class can have a constructor to initialize its objects.
The data members of an interface are always public.The data members of a class can be public, private,orprotected`.
An interface can extend more than one interface but cannot implement an interface.A class can only extend only one class and can implement several interfaces.

Congratulations!

After reading this article, You are now proficient in the concept of Classes and Interfaces in TypeScript and you are ready to implement both in your projects easily.

Conclusion

  • Through this article, you have learned about the declaration and working of Classes & Interfaces.
  • You have also gone through a very important concept of object-oriented programming which is Inheritance.
  • We get to know how the interface has been declared as a type and function type.
  • We get to know about the factors that are responsible to create differences between both.
  • Hope this article has provided you with the relevant information concerning the concept of Classes and Interfaces in TypeScript.