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
- interface IPerson {
- name: string;
- age: number;
- greet: (nm: string) => string;
- getLocation(): string;
- }
Interface as Type
Interface in TypeScript can be used to define the type and also to implement it in the class.
- let p1: IPerson = {
- name: 'Virat',
- age: 40,
- greet: function(nm) {
- return "Hi " + nm;
- },
- getLocation(): string {
- return 'Pune';
- }
- }
Interface as Function Type
Used to define a type of a function, that ensures the function signature
- interface SearchFunc {
- (source: string, subString: string): boolean;
- }
Interface for Array Type / Indexable Type
- interface ArrayList {
- [index: number]: string;
- }
- let myArr: ArrayList;
- myArr = ['Sachin', 'Virat'];
- console.log(myArr[0]);
Optional Property
Optional properties, marked with a "?", objects may or may not define these properties
- interface IPlayer {
- playerNo: number;
- playerName: string;
- playerCity ? : string;
- }
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.
- interface IPoint {
- readonly x: number;
- readonly y: number;
- }
- let point1: IPoint = {
- x: 11,
- y: 22
- };
- point1.x = 5
Extending Interfaces
Interfaces can extend one or more interfaces.
- interface IPerson {
- name: string;
- gender: string;
- }
- interface IPlayer extends IPerson {
- playerNo: number;
- }
Implementing Interface over Class
Interfaces can be implemented with a class. Class implementing the interface needs to strictly conform the structure of the interface
- interface IPlayer {
- playerNo: number;
- name: string;
- getRuns: (string) => number;
- }
- class Player implements IPlayer {
- playerNo: number;
- name: string;
- constructor(no: number, name: string) {
- this.playerNo = no;
- this.name = name;
- }
- getRuns(playerName: string): number {
- return 12312;
- }
- }
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.
- class Employee {
- empNo: number;
- empName: string;
- constructor(no: number, name: string) {
- this.empName = name;
- this.empNo = no;
- }
- grtSalary(): number {
- return 10000;
- }
- }
Extending class from another class - Inheritance and Method Overriding
Constructors for derived classes must contain a super call
- class Car {
- run(speed: number = 0) {}
- }
When a child class defines its own implementation of a method from the parent class, it is called method overriding.
- class Mustang extends Car {
- constructor() {
- super();
- }
- run(speed = 140)
- }
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__