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.