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
labelproperty, 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
LabeledValuedefines the shape of the object that is expected, ensuring it has alabelproperty. - The function
printLabelnow expects an object of typeLabeledValue.
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"
};IEmployeeextends theIPersoninterface, meaning it inherits the properties ofIPersonand 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
IEmployeeinterface defines the structure that theEmployeeclass must adhere to. - The class
Employeeimplements the interface, providing theempCode,name, andgetSalarymethod.
Key Points:
- Interfaces define the structure of an object, including its properties and methods.
- Interfaces can be extended to create more complex types by inheriting properties and methods from other interfaces.
- Classes can implement interfaces, ensuring the class adheres to the structure defined by the interface.