Learning TypeScript. Part 2: Interfaces

TypeScript provides excellent support for interfaces. For the beginners:

What is the interface?

Lets see if analogy can help here: for example lets take a factory. a factory requires that all the engines being built have a standard “interface” (for example 2 buttons: green/red, start/stop). So that when the new engine comes out we don’t need to study some new technics – there are still that 2 buttons from the mental example. If we change the physical engines with classes – then the consistent behavior in all that classes can be explained in the interface.

For example in TypeScript interface can be used to deny compilation in case some class has not implemented the needed functionality. Interface definition keyword is `interface`.

Example:


interface IEngine{
	 Start(): boolean;
	 Stop(): boolean;
}

class V8 implements IEngine{ // We will talk about classes shortly
	 Start(): boolean{
		alert('v8 started');
		return true;
	}
	
	Stop(): boolean{
		alert('stopped v8');
		return true;
	}
}

var engine = new V8();
engine.Start();

As in classic OOP languages this feature adds polymorphism capability to TypeScript.


Resources

SOLID principle

Learning TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *