Function Interface in TypeScript

Rana Hasnain Khan Jul 25, 2022
Function Interface in TypeScript

We will introduce a function interface in TypeScript with examples.

Interface As Function Type in TypeScript

The interface allows us to create a parent structure used throughout the application for certain classes or functions. Any change in the structure at any stage of the application will give an error.

The interface can validate the specific structure of properties, objects returned from functions, or objects passed as parameters. We can easily define an interface using the keyword interface and include the properties and method.

We can declare methods using the function or an arrow function. As shown below, let’s see an example and create an interface for courses.

Code:

# typescript
interface CsCourse {
    subCode: number;
    subName: string;
    instructor(id): string;
    getCgpa: (number) => number;
}

Let’s use this interface for our functions.

Code:

# typescript
interface Course
{
    (subCode: number, subName: string): void;
};
function addSub(subCode:number, subName:string):void {
    console.log('Adding Subject: Subject Code = ' + subCode + ', Subject Name = ' + subName)
}

function updateSub(subCode:number, subName:string):void {
    console.log('Updating Subject: Subject Code = ' + subCode + ', Subject Name = ' + subName)
}

let sub: Course = addSub;
sub(301, 'Compiler Construction');

sub = updateSub;
sub(101, 'Introduction to Programming');

Output:

function interface example in typescript

By creating an interface, we can follow the structure of the properties or functions and ensure that the same structure is followed throughout the application. Using interfaces for these properties makes our application secure, and we can ensure that the correct data is being sent to the functions.

Now, let’s try to assign a new function with a different signature than the signature we defined in the interface course.

Code:

# typescript
function delSub(subCode:number):void {
    console.log('Subject deleted.')
}

let sub: Course = delSub;

The code above will give the compiler error.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - TypeScript Interface