TypeScript - Interfaces #1
UPDATE : Based on TypeScript 2.1.4
The feature TypeScript has, but Javascript doesn’t have is Data Types. ‘Javascript doesn’t have’ means that ‘Data Types’ can neither be assigned in Javascript nor be understood by the browser engine. Data Type information in TypeScript code is processed by the TypeScript transcompiler and it generates type-validated Javascript code. In other words TypeScript enforces strict data type rules. This may be easy if the code has primitive data types like number,string, boolean only, but not for a code segment that has many classes, instances and other complex objects. Interfaces is the solution to this problem. It acts as a ‘contract’ between two code segments and ensures that the final code is type-safe.
Consider the following example. Here we have a list players
and a function addPlayer
to add a player to the list. Inside the function it is checked that the passed object has all the required properties.
What are the drawbacks here
- The function
addPlayer
has to validate the passedplayer
object - The
if
condition checks inaddPlayer
is incomplete as it is not checking the type of each property - If there are
n
required properties forplayer
, a minimum ofn
conditions are required inif
- More code has to be written to perfectly validate the data passed
TypeScript solves all these problems. See the example below which makes use of ‘Data Types’ to validate the data passed.
Now the function addPlayer
is stating that it is expecting and object of structure {name:string, age:number, place:string}
. This ‘contract’ is called Interface.
Now onwards please make sure that compiler option strictNullChecks
is enabled
> tsc --strictNullChecks <script file>
Let us rewrite the code using TypeScript keyword interface
Now assume that
p1
is retrieved using a function getData
. So the code will beNow you can see that the
Player
is acting as a ‘contract’ between different code segments. This is not a new thing a for those who are are familiar with Java or C#, but its a new thing in Javascript.For Functions
Interfaces can be defined for functions also.See the example below.
Classes and Interfaces
A
class
can implement an interface. Example below