An interface in TypeScript is used to define the shape of an object. It can specify the properties and methods that an object must have, but it doesn’t provide the implementation.

Example 1: Basic Interface

function printLabel(labeledObj: { label: string }) {
  console.log(labeledObj.label);
}
 
let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);
  • This function accepts an object with a label property, but it’s defined inline.
  • You can improve this with an interface.

Example 2: Using an Interface to Define Object Shape

interface LabeledValue {
  label: string;
}
 
function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}
 
let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);
  • The interface LabeledValue defines the shape of the object that is expected, ensuring it has a label property.
  • The function printLabel now expects an object of type LabeledValue.

Example 3: Extending Interfaces

interface IPerson {
  name: string;
  gender: string;
}
 
interface IEmployee extends IPerson {
  empCode: number;
}
 
let empObj: IEmployee = {
  empCode: 1,
  name: "Bill",
  gender: "Male"
};
  • IEmployee extends the IPerson interface, meaning it inherits the properties of IPerson and adds its own (empCode).
  • This shows how interfaces can be extended to create more complex types.

Example 4: Implementing an Interface in a Class

interface IEmployee {
  empCode: number;
  name: string;
  getSalary: (empCode: number) => number;
}
 
class Employee implements IEmployee {
  empCode: number;
  name: string;
 
  constructor(code: number, name: string) {
    this.empCode = code;
    this.name = name;
  }
 
  getSalary(empCode: number): number {
    return 20000;
  }
}
 
let emp = new Employee(1, "Steve");
  • The IEmployee interface defines the structure that the Employee class must adhere to.
  • The class Employee implements the interface, providing the empCode, name, and getSalary method.

Key Points:

  1. Interfaces define the structure of an object, including its properties and methods.
  2. Interfaces can be extended to create more complex types by inheriting properties and methods from other interfaces.
  3. Classes can implement interfaces, ensuring the class adheres to the structure defined by the interface.