Skip to main content

Interface

Interface

//almost same as type aliases
//use them to create reusable modular types that describe the shape of objects
interface Person{
name:string;
age:number;
}
const sayHappyBirthday = (person:Person)=>{
retun `Hey ${person.name}, congrats on turning ${age}`;
}

sayHappyBirthday({name:'Bob',age:31});

Optional

interface Person{
first:string;
last:string;
nickname?:string;
}
const tom:Person={first:'tom',last:'page'};

Method

interface Person{
readonly id:number;
first:string;
last:string;
nickname?:string;
sayHi:()=>string; //accept zero argument and returns a string
}

const p:Person={
id:222,
first:'tom',
last:'Kingston',
nickname:'tommy',
sayHi: () =>{return `Hi I am ${this.first}`;}
}

Reopening Interface

interface File{filename:string;}
interface File{size:number;}
const f:File={filename:'aaa.jpg',size:9}

Extending Interface

interface File{filename:string;}
interface ImgFile extends File{size:number;}
const f:ImgFile={filename:'aaa.jpg',size:9}

Multiple Extend (multi-inheritance)

interface Employee{name:string;}
interface Admin{type:string;}
interface User extends Employee,Admin{username:string;}
const a:User={name:'Marilyn',type:'system',username:'mary'}