Explain the Concept of Interfaces in TypeScript ?

The interfaces in TypeScript are used to define a particular type of object to which the objects must adhere. They act like a blue-print for the objects and define the structure of the objects. They are mainly used to type the keys of the object by specifying their types and then use the declared interface to type the object in the code.

Syntax:

interface interface_name{
key1: type1;
key2: type2;
}
const object_name: interface_name = {
// Object values
}

Example: The below code explains the use of the interface to type an object in TypeScript.

Javascript
interface myInterface {
    name: string;
    desc: string;
    est: number;
}

const myObj: myInterface = {
    name: "w3wiki",
    desc: "A Computer Science Portal",
    est: 2009
}

console.log("Welcome to ", myObj.name, ", ",
    myObj.desc, ", ", "Established in: ",
    myObj.est);

Output:

Welcome to w3wiki, A Computer Science Portal, Establishe in: 2009.

Example: In this example we defines an interface Calculate for functions with two number parameters and a number return type. It implements addition and subtraction functions, then uses a generic operate function to execute them.

JavaScript
// Define an interface for a function signature
interface Calculate {
    (x: number, y: number): number;
}

// Define a function that adheres to the interface
const add: Calculate = (a, b) => a + b;

// Define another function that adheres to the interface
const subtract: Calculate = (a, b) => a - b;

// Define a generic function that takes a function adhering to the Calculate interface
function operate(operation: Calculate, x: number, y: number): number {
    return operation(x, y);
}

// Use the operate function with different operations
console.log("Addition:", operate(add, 5, 3)); 
console.log("Subtraction:", operate(subtract, 10, 4)); 

Output:

Addition: 8 
Subtraction: 6

Contact Us