Fundamentals Of TypeScript - Object Oriented Concepts

This article covers the below points,
  • Interface
  • Class
  • Type Gaurd
  • Generics
  • Decorators
  • Namespace
  • Modules

Interface

 
An interface is a contract in the application. It defines the syntax for classes to follow. Classes that implement the interface must follow the structure provided by the interface. TypeScript compiler does not convert the interface to JavaScript. It uses for type checking. this is called "duck typing" or "structural subtyping".
 
Interface can include properties and method declarations using a function or an arrow function
  1. interface IPerson {  
  2.     name: string;  
  3.     age: number;  
  4.     greet: (nm: string) => string//arrow function declaration  
  5.     getLocation(): string//normal function declaration  
  6. }   
Interface as Type
 
Interface in TypeScript can be used to define the type and also to implement it in the class.
  1. let p1: IPerson = {  
  2.     name: 'Virat',  
  3.     age: 40,  
  4.     greet: function(nm) {  
  5.         return "Hi " + nm;  
  6.     },  
  7.     getLocation(): string {  
  8.         return 'Pune';  
  9.     }  
  10. }  
Interface as Function Type
 
Used to define a type of a function, that ensures the function signature
  1. interface SearchFunc {  
  2.     (source: string, subString: string): boolean;  
  3. }  
Interface for Array Type / Indexable Type
  1. interface ArrayList {  
  2.     [index: number]: string;  
  3. }  
  4. let myArr: ArrayList;  
  5. myArr = ['Sachin''Virat'];  
  6. console.log(myArr[0]);  
Optional Property 
 
Optional properties, marked with a "?", objects may or may not define these properties
  1. interface IPlayer {  
  2.     playerNo: number;  
  3.     playerName: string;  
  4.     playerCity ? : string//optional property  
  5. }  
Readonly Properties 
 
Some properties should only be modifiable when an object is first created. you can specify this by putting read-only before the name of the property.
  1. interface IPoint {  
  2.     readonly x: number;  
  3.     readonly y: number;  
  4. }  
  5. let point1: IPoint = {  
  6.     x: 11,  
  7.     y: 22  
  8. };  
  9. point1.x = 5 // error  
Extending Interfaces 
 
Interfaces can extend one or more interfaces.
  1. interface IPerson {  
  2.     name: string;  
  3.     gender: string;  
  4. }  
  5. interface IPlayer extends IPerson {  
  6.     playerNo: number;  
  7. }  
Implementing Interface over Class
 
Interfaces can be implemented with a class. Class implementing the interface needs to strictly conform the structure of the interface
  1. interface IPlayer {  
  2.     playerNo: number;  
  3.     name: string;  
  4.     getRuns: (string) => number;  
  5. }  
  6. class Player implements IPlayer {  
  7.     playerNo: number;  
  8.     name: string;  
  9.     constructor(no: number, name: string) {  
  10.         this.playerNo = no;  
  11.         this.name = name;  
  12.     }  
  13.     getRuns(playerName: string): number {  
  14.         return 12312;  
  15.     }  
  16. }   

Class

 
TypeScript uses classes to avail the benefits of object-oriented techniques like encapsulation and abstraction. The class in TypeScript is compiled to plain JavaScript functions by the TypeScript compiler to work across platforms and browsers.
 
TypeScript compiler will convert the above class to javascript code using a closure.
  1. class Employee {  
  2.     empNo: number;  
  3.     empName: string;  
  4.     constructor(no: number, name: string) {  
  5.         this.empName = name;  
  6.         this.empNo = no;  
  7.     }  
  8.     grtSalary(): number {  
  9.         return 10000;  
  10.     }  
  11. }  
Extending class from another class - Inheritance and Method Overriding

Constructors for derived classes must contain a super call
  1. class Car {  
  2.     run(speed: number = 0) {}  
  3. }  
When a child class defines its own implementation of a method from the parent class, it is called method overriding.
  1. class Mustang extends Car {  
  2.     constructor() {  
  3.         super();  
  4.     }  
  5.     run(speed = 140)  
  6. }  
Abstract classes are mainly for inheritance where other classes may derive from them. We cannot create an instance of an abstract class. An abstract class typically includes one or more abstract methods or property declarations. The class which extends the abstract class must define all the abstract methods.
 

Type Guard

 
Type Guards allow you to narrow down the type of an object within a conditional block.
 
TypeScript is aware of the JavaScript type of and instead of operators. If you use these in a conditional block, TypeScript will understand the type of the variable to be different within that conditional block.
 
In 
 
The in operator does a safety check for the existence of a property on an object and can be used as a type guard.
 
Literal Type Guard 
 
You can use === / == / !== / != to distinguish between values
 
User-Defined Type Guards
 

Generics

 
Generics provide a way to make components work with any data type and not restrict to one data type. Generics in TypeScript are almost similar to C# generics.
 
Suppose you have 'any' type array variable that allows to store number where was string and vice versa. To solve this problem, TypeScript has introduced Generics. You will get an error at compile-time only rather than getting it at runtime.
 
Generics makes use of type variables <Y>, a special kind of variable that denotes types. The type variable remembers the type that the user provides and works only with that particular type, called preserving the information.
 
Generics support multiple types of data types as well.
 
Generics Class
 
You can apply constraints also on Generics as generic type has to be extended from a specific type or implemented specific interface.
 

Decorators

 
Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are available as an experimental feature of TypeScript.
  • To enable experimental support for Decorators, you must enable the experimental Decorators compiler option either on the command line or in your tsconfig.json
  • A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property or parameter
  • Decorators use the form expression where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
  • Decorator Factory - it is simply a function that returns the expression that will be called by the decorator at runtime.

Namespace

 
A namespace is used for the logical grouping of different functionalities. A Namespacecan includes classes, interfaces, functions & variables to support a single or a group of related functionalities
 
By default, namespace components cannot be used in other modules or other namespaces. Each component must be exported to make it accessible outside, using the export keyword
 

Modules

 
Modules are executed within their own scope, not in the global scope, which means variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using any of the export forms.
 
On the other hand, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.
 
Modules are declarative, the relationships between modules are specified in terms of imports and exports at the file level.
 
Module Loaders
  • RequireJS - loader for modules in AMD format
  • SystemJS - loader for modules in AMD, CommonJS, UMD, or System.register format
Module Bundlers
  • Browserify - bundler for CommonJS modules
  • Webpack - bundler for AMD, CommonJS, ES6 modules.
These are the Object-Oriented concepts in TypeScript.
 
_Happy Coding__