The open blogging platform. Say no to algorithms and paywalls.

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 unit

x, 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 property

We 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 property

We 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 methods

Creating 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Ā John,Ā Paul,Ā Bob,Ā MaryĀ -- 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 image

Please 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 image

Please 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




Continue Learning