- 4 years ago
- Afaq Arif
- 6,485 Views
-
2
In this chapter, we will discuss in detail TypeScript interfaces with examples. We will also study the relationship between interfaces, arrays, and inheritances.
An interface defines the syntax that any system must attach to. In simple, it is a syntactical arrangement that a system should agree to.
Interfaces define properties, methods, and events, which are the elements of the interface. Interfaces have the statement of the members. It is the responsibility of the extracting class to define the members. It often helps in providing a standard structure that the obtaining classes would follow.
Let’s consider an object.
var person = {
FirstName:"Tom",
LastName:"Hanks",
sayHi: ()=>{ return "Hi"}
};
If we consider the signature of the object, it could be.
{
FirstName:string,
LastName:string,
sayHi()=>string
}
We can define it as an interface to reuse the signature across objects.
Declaring Interfaces
We can state an interface with the interface keyword. The syntax to state an interface is as follows.
Syntax
interface interface_name {
}
Example: Interface and Objects
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
console.log("Customer Object ")
console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())
var employee:IPerson = {
firstName:"Jim",
lastName:"Blakes",
sayHi: ():string =>{return "Hello!!!"}
}
console.log("Employee Object ")
console.log(employee.firstName);
console.log(employee.lastName);
The example defines an interface. The customer object is of the type IPerson. Therefore, the object should explain all properties as defined by the interface.
We can still consider another object with the next signature as IPerson because it is used by its size.
The following JavaScript code runs on composing.
//Generated by typescript 1.8.10
var customer = { firstName: "Tom", lastName: "Hanks",
sayHi: function () { return "Hi there"; }
};
console.log("Customer Object ");
console.log(customer.firstName);
console.log(customer.lastName);
console.log(customer.sayHi());
var employee = { firstName: "Jim", lastName: "Blakes",
sayHi: function () { return "Hello!!!"; } };
console.log("Employee Object ");
console.log(employee.firstName);
console.log(employee.lastName);
The output of the above example code is as follows.
Customer object
Tom
Hanks
Hi there
Employee object
Jim
Blakes
Hello!!!
We can not convert interfaces to JavaScript. It’s just part of TypeScript. If you see the screenshot of TS Playground tool there is no JavaScript released while stating an interface, unlike a class. So interfaces have zero runtime JavaScript results.
Union Type and Interface
The following example shows the use of Union Type and Interface.
interface RunOptions {
program:string;
commandline:string[]|string|(()=>string);
}
//commandline as string
var options:RunOptions = {program:"test1",commandline:"Hello"};
console.log(options.commandline)
//commandline as a string array
options = {program:"test1",commandline:["Hello","World"]};
console.log(options.commandline[0]);
console.log(options.commandline[1]);
//commandline as a function expression
options = {program:"test1",commandline:()=>{return "**Hello World**";}};
var fn:any = options.commandline;
console.log(fn());
It runs the following JavaScript code on composing.
//Generated by typescript 1.8.10
//commandline as string
var options = { program: "test1", commandline: "Hello" };
console.log(options.commandline);
//commandline as a string array
options = { program: "test1", commandline: ["Hello", "World"] };
console.log(options.commandline[0]);
console.log(options.commandline[1]);
//commandline as a function expression
options = { program: "test1", commandline: function () { return "**Hello World**"; } };
var fn = options.commandline;
console.log(fn());
Its output is as follows.
Hello
Hello
World
**Hello World**
Interfaces and Arrays
You can use an interface to state the key type of an array used. You can also define the kind of entry that the array contains with an interface. The index can be of type string or type number.
Example
interface namelist {
[index:number]:string
}
var list2:namelist = ["John",1,"Bran"] //Error. 1 is not type string
interface ages {
[index:string]:number
}
var agelist:ages;
agelist["John"] = 15 // Ok
agelist[2] = "nine" // Error
Interfaces and Inheritance
You can continue an interface by other interfaces. In simple, we can get an interface from other interfaces. Typescript allows an interface to obtain from multiple interfaces.
We use the extends keyword to implement inheritance among interfaces.
Syntax: Single Interface Inheritance
Child_interface_name extends super_interface_name
Syntax: Multiple Interface Inheritance
Child_interface_name extends super_interface1_name,
super_interface2_name,…,super_interfaceN_name
Example: Simple Interface Inheritance
interface Person {
age:number
}
interface Musician extends Person {
instrument:string
}
var drummer = <Musician>{};
drummer.age = 27
drummer.instrument = "Drums"
console.log("Age: "+drummer.age) console.log("Instrument: "+drummer.instrument)
It shows following JavaScript code on composing.
//Generated by typescript 1.8.10
var drummer = {};
drummer.age = 27;
drummer.instrument = "Drums";
console.log("Age: " + drummer.age);
console.log("Instrument: " + drummer.instrument);
Its output is as follows.
Age: 27
Instrument: Drums
Example: Multiple Interface Inheritance
interface IParent1 {
v1:number
}
interface IParent2 {
v2:number
}
interface Child extends IParent1, IParent2 { }
var Iobj:Child = { v1:12, v2:23}
console.log("value 1: "+this.v1+" value 2: "+this.v2)
The object Iobj is of the type interface leaf. Currently, it has two properties- v1 and v2 respectively according to the property of inheritance. So it must possess these qualities now.
It will generate following JavaScript code on composing.
//Generated by typescript 1.8.10
var Iobj = { v1: 12, v2: 23 };
console.log("value 1: " + this.v1 + " value 2: " + this.v2);
The output of the above code is as follows.
- 4 years ago
- Afaq Arif
- 6,485 Views
-
2