Interfaces and Classes in TypeScript/Angular

What is Angular (Part 6.3) / What is TypeScript?

image

How it works… | How to start…

If you haven’t covered Part — 6.2 of this series, I recommend you to check this link → Arrow Functions in TypeScript | Part — 6.2 | of series What Angular is? 🤷🏻‍♂️ What TypeScript is?

Fundamentals of TypeScript👇

  1. Type annotations

  2. Arrow functions

  3. Interfaces

  4. Classes

  5. Constructors

  6. Access modifiers

  7. Properties

  8. Modules

6.3 Interfaces

The better approach to use Custom Types in TypeScript is by using Interfaces. An interface is a structure that defines the syntax for classes to follow. Along with functions, an interface can also be used with a Class as well to define custom types. An interface is an abstract type, it does not contain any code as a class does.

What is the difference between Interface and Class in TypeScript?

A class is a blueprint from which we can create objects that share the same configuration — properties and methods. An interface is a group of related properties and methods that describe an object, but neither provides implementation nor initialization for them.

👉 Let’s define an Interface

  • Interface Name: Point
  • Then within the block of Interface add properties as x and y
  • The name of the Interface should always use Pascal naming convention that is Starts with Uppercase. Look below P of the name interface Point is starts with uppercase.
interface Point {
  x: number;
  y: number;
}

Look below the example of Inline Annotation — Check this link 👉 Click here to read more about Inline Annotation.

let drawNewLine = function (point1: {x: number, y: number}, point2: {x: number, y: number}) {
    console.log("Code to draw a line comes here...");
}

We can simplify above code by declaring Interface.

  • It’s much cleaner and

  • Can be re-use in multiple places

let drawNewLine = function (point1: Point, point2: Point) {
  console.log("Code to draw a line comes here...");
};

Look above👆 point1 and point2 objects are pointing to Interface Point.

Cohesion

The concept of Cohesion: means the things that are related should always be part of one unit. They should go together this is called Cohesion.

This example of Interface defines the shape of a Point object (Look👇 line no. 1) and below that we have standalone function (Look👇 line no. 6) and this is where we have violated the Cohesion principle.

So, the concept of drawNewLine is highly related to Point interface. Now this creates a problem when we create another function lengthOfLine (Look👇 line no. 10). Again we have violated the Cohesion principle: We have two functions ( drawNewLine and lengthOfLine ) which are separate from the Point object. They all should be a part of one unit.

x, y and drawNewLine, lengthOfLine all should be a part of single unitx, y and drawNewLine, lengthOfLine all should be a part of single unit

In Object-oriented-programming we call this Unit Class for class, group, properties, functions that are highly related.

Means the things that are related should always be part of one unit but in this case we can not move these function inside interface because interfaces are purely for declarations they cannot include an implementation.

⭐️ Now, look what we can doo…

  • We can add a function declaration inside an interface that takes no parameters and returns void means this function does not returns anything. Look👇below.

  • Since parameters x and y are already a part of interface Point that is why we do not need to pass parameters inside the drawNewLine function. These functions can directly access properties x and y in the same unit.

  • In interfaces we cannot have implementation we can only have signature of a function.

    interface Point { x: number, y: number, drawNewLine: () => void; }

The compiler understand from the interface that it has two properties ( x , y ) and a method ( drawNewLine ) declared--and its implementation is somewhere else.

As we know we can only do declarations in interfaces, we can not do implementation in interfaces and for implementation we need classes.

⭐️ More in Interfaces

  • Optional Properties: Not all properties of an interface may be required. Some exist under certain conditions or may not be there at all. We can specify this by putting ? (question mark) after the name of the property. Look👇below at line no. 4 & 5 -- these optional params can be passed optionally while calling a function. Look👇below at line no. 24 & 28.

We can specify Optional Properties by putting ? (question mark) after the name of the propertyWe can specify Optional Properties by putting ? (question mark) after the name of the property

  • Readonly Properties: Some properties should only be modifiable when an object is first created. We can specify this by putting readonly before the name of the property. Look👇below at line no. 4 & 5.

We can specify Readonly Properties by putting readonly before the name of the propertyWe can specify Readonly Properties by putting readonly before the name of the property

  • Readonly vs Const: The easiest way to remember whether to use readonly or const is to ask whether you're using it on a variable or a property. Variables uses **const whereas properties uses readonly. Now, a variable can be a local variable, defined inside a procedure and available only within that procedure. and a property is a member of classes, structures, and interfaces.

6.3 Classes

An interface has fully abstract methods i.e. methods with nobody. An interface is syntactically similar to the class but there is a major difference between class and interface that is a class can be instantiated, but an interface can never be instantiated. The members of a class can be private, public or protected. and the members of an interface are always public. An interface says what needs to be done. A class says how it is done.

Classes are the groups of variables (properties) and functions (methods) that are highly related.

⭐️ Applying Cohesion Principle

Applying Cohesion Principle by using Class instead of Interface. Here x and y are the fields to store data, drawNewLine and lengthOfLine are the functions.

image

Now, we have everything is in one Class. We have two fields and two methods. When a function is a part of class we call it a method.

⭐️ It’s time⏳to Create an object of Class & call methods

  • Create an object of class -- Look👇below at line no. 17
  • Call a method without setting values of properties x and y -- Look👇below at line no. 18 -- This returns the output 👉 x: undefined, y: undefined
  • Call a method after setting values of properties x and y -- Look👇below at line no. 22 -- This returns the output 👉 x: 1, y: 2

Creating Class | Create an object of Class | & call methodsCreating Class | Create an object of Class | & call methods

Look above👆 this is how we define and use the classes in our programs.

let pointObj = new Point();

⭐️ Best example of Class and Object: Think of Human -- here Human is a class and when we create instance of this class Human we get JohnPaulBobMary -- these all are objects.

  • Human👤 -- Human is a class.

  • John👨‍🌾, Paul👨‍🎓, Bob👨‍💻, Mary👩‍💼 -- are objects of class Human.

    Next important concept…

⭐️ Implementing an interface / Class implements an Interface:

All the methods in interface are declared with empty body and are public, and all fields are public, static and final by default. A class that implement interface must implement all the methods and fields declared in the interface.

  • We cannot write any code inside the methods of an interface, nor we can initialize variable — Look👇below at line no. 3 and 4 — empty body, that is only declaration allowed.

  • We can write code inside the methods of a class, also we can initialize variables — Look👇below at line no. 9 and 11 — method implementation.

Please carefully read all the comments in the imagePlease carefully read all the comments in the image

Next important concept…

⭐️ Extending an Interface / Interface extends another Interface:

An interface can extend another interface in the same way that a class can extend another class. This allows us to copy the members of one interface into another, which gives us more flexibility in how we separate our interfaces into reusable components. The extends keyword is used to extend an interface.

Look👇below at line no. 10 — variable (square) of type Square has access to the member of other interfaces (Shape and PenStroke) because Square has extended Shape and PenStroke.

Please carefully read all the comments in the imagePlease carefully read all the comments in the image

Things to remember before 👋👋

Class extends another Class (covered in this👇 article)
https://medium.com/@AnkitMaheshwariIn/constructors-and-access-modifiers-in-typescript-22a2d6188780#09ed
Class implements an Interface (covered in this👇 article)
https://medium.com/@AnkitMaheshwariIn/interfaces-and-classes-in-typescript-part-6-3-7fee77b7518b#ebd8
Interface extends another Interface (covered in this👇 article)
https://medium.com/@AnkitMaheshwariIn/interfaces-and-classes-in-typescript-part-6-3-7fee77b7518b#0b2d

This is it’s about Interfaces and Classes — see you in the next part 👋👋 to cover another concept Constructors.

If you haven’t covered Part — 6.2 of this series, I recommend you to check this link → Arrow Functions in TypeScript | Part — 6.2 | of series What Angular is? 🤷🏻‍♂️ What TypeScript is? Stay tuned for Part — 6.4 https://medium.com/@AnkitMaheshwariIn

Learn More

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics