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š
-
Interfaces
-
Classes
-
Constructors
-
Access modifiers
-
Properties
-
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
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
- 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
- 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.
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
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
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
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