Interface
Defines a “shape” for JavaScript objects, functions and more
Creates a contract for code
Little Background
Blueprint for an object (loosely)
function printMe(obj){
console.log(obj.name);
}
printMe({ name: "Kamal" }); // Kamal
printMe({ age: 20 }); // undefined
// solution to above problem
interface person{
name: string;
age?: Number; // optional
}
function printMe(obj: person){
console.log(obj.name, obj.age || 12);
}
printMe({ name: "Kamal" });
Basic Interfaces
Basic interfaces in TypeScript are for the type Object
interface XYZ {
name: string;
color: string;
}
var summer : XYZ = {name:”Summer”,color:”Brown”} // ok
var lady : XYZ = {name:”Lady”} // throws error. Missing property “color”
var ghost : XYZ = {name:”Ghost”,color:”white”,silent:true} // throws error. XYZ has no property silent.
Optional Properties
Interfaces can have optional properties
interface Stark {
name: string;
location? : string;
}
var bran : Stark = {name: “Bran”,location:”Summer”} // OK
var sansa : Stark = {name: “Sansa”} // Also OK. Direwolf property is optional.
Function types
Interfaces can describe Functions as well
interface Salute {
(name: string): string;
}
var bonjour: Salute = function(n: string): string { return "Hello "+ n };
console.log(bonjour('baby')); // Hello baby
Array Types
Interface can define both the kind of key an array uses and the type of entry it contains
Index can be of type string or type number
interface NameList {
[index: number]: string;
}
var list2 : NameList = ['Hemant',1,"Singh"] // error. 1 is not type string
interface Ages {
[index: string]: number;
}
var ages: Ages = []; ages['Hemant'] = 15; // ok; ages[2] = ‘nine’; // error
Class Types
Interfaces can define a class similar to Java
interface Person {
age: number;
}
class Stark implements Person {
age: number;
location: string;
}
Extending Interfaces
Interfaces can extend other interfaces
interface Person {
age: number;
}
interface Musician extends Person { instrument: string; }
var s: Musician = { age: 20, instrument: 'Papa' };
console.log(s);
Hybrid Interfaces
TypeScript interfaces can describe something that is a function and an object at the same time. Because, JavaScript!
Interface Jump {
(distance: number) : string;
height: number;
}
var j : Jump;
j(50);
j.height = 12;
Last updated
Was this helpful?