Typescript > Interfaces

Basic Interfaces in Typescript

How to define and use interfaces in TypeScript?


In previous post, we learnt about how to define different data types in TypeScript. In this post, we shall learn what is Interface and how to create and use it.

Declaring, implementing and using Interface in TypeScript

As in other programming languages, "Interfaces are contracts to enfore certain rules". The same principle of Interface applies in the TypeScript as well however TypeScript is not as strict as other programming languages interfaces are. TypeScript type-checking only checks for the shape of the interfaces (whether the least expected properties are there or not). This type of checking is also called duck typing or structural subtyping.

Below code snippets shows how to declare, implement and use the interface in TypeScript.

First we have declared the interface using interface keyword. It is not mandatory to keep the name of the Interface starting with "I", we have just followed the standard naming convention as followed in other programming languages while declaring the interface.

Declaring, implementing and using Interface in TypeScript

// declaring interface
interface IPerson {
    name: string;
}

// using the interface
function Details1(thisPerson: IPerson) {
    // alert(thisPerson.name);
}

// calling the function that is using interface
var myDetail1 = { age: 50, name: "Sheo" };
var myDetail11 = { name: "Sheo Narayan", address : "Hyderabad", age :50 };
Details1(myDetail1);
Details1(myDetail11);

After that we have used IPerson interface into Details1 function. In this function, we instruct that Details1 function should accepts an object that is described in IPerson interface. The IPerson says that the object should have one property named "name" and that should be of string type.

Next part of code is how to call the function that users IPerson interface.

  • In 1st case we call the Details1 function with an object that has age and name properties. Notice that we have not mentioned anywhere that myDetail1 object that we have passed to the function implements IPerson interface. As long as the object passed to the function has name property in it, TypeScript has no problem.

  • In 2nd case, we can see that the object passed to Details1 function has different propertiers in different order despite it works

With the above examples we can notice that TypeScript type-checkers only care about the shape (property names that exists) of the object, it ignores rest.

After compiling above TypeScript code, we get following JavaScript output.

JavaScript Output

// using the interface
function Details1(thisPerson) {
    alert(thisPerson.name);
}

// calling the function that is using interface
var myDetail1 = { age: 50, name: "Sheo" };
var myDetail11 = { name: "Sheo Narayan", address: "Hyderabad", age: 50 };
Details1(myDetail1);
Details1(myDetail11);

Declaring optional properties in the Interface of TypeScript

As against other programming language Interfaces, TypeScript interface allows us to declare optional properties also where we can mark few properties as optional. In this case, type-checkers checks for only mandatory properties on the object passed to the function implementing this interface.

Optional properties are declared by suffixing the property name with "?".

In the 1st part of the code we have declared IPersonOptional interface with age as optional property.

In the 2nd part of the code snippet, we have used this interface in the DetailsOptional function. Inside this function, we have checked whether passed object has age property value set or not and depending on that we have given alert to the user.

interface IPersonOptional {
    name: string,
    age?: number;
}

// using the interface
function DetailsOptional(personalOptional: IPersonOptional) {
    if (personalOptional.age) {
        alert("Your name is: " + personalOptional.name + " and age is: " + personalOptional.age);
    }
    else {
        alert("Your name is: " + personalOptional.name);
    }
}
// calling the function that is using interface
DetailsOptional({ name: "Sheo" });
DetailsOptional({ name: "Sheo", age: 60 });

In the last part of the above code snippet, we have called the function. In 1st call we called with just name property (Shows alert as 'Your name is: Sheo') and 2nd time we called with both property (Shows alert as 'Your name is: Sheo and age is: 60').

Compiling above code gives below JavaScript output.

JavaScript Output

// using the interface
function DetailsOptional(personalOptional) {
    if (personalOptional.age) {
        alert("Your name is: " + personalOptional.name + " and age is: " + personalOptional.age);
    }
    else {
        alert("Your name is: " + personalOptional.name);
    }
}
// calling the function that is using interface
DetailsOptional({ name: "Sheo" });
DetailsOptional({ name: "Sheo", age: 60 });

In case we misspelled any property names, the TypeScript compiler throws error.

Describing function types with Interfaces in TypeScript

In all above examples, interfaces have been used to describe the object with properties. In TypeScript, interfaces can also be used to describe the function type. To do this, we give the interface a call signature.

This necessarily means that declare a function with parameters and return type.

In 1st part of the code below, we have declared an Interface named IMath with a and b as parameter of number type and the return type should also be number.

In the 2nd part of the code snippet, we have used above function type interface by creating a variable of this function type and assigning it to a function of the same type.

The add variable is declared of IMath type and a function is assigned to it that does calculation and returns number. Next, we have called the add function with two parameter that returns sum of two numbers (number data type).

If we try to change the return type to string, the TypeScript type-checker throws error.

interface IMath {
    (a: number, b: number): number;
}

// using the interface
var add: IMath;
add = function (a: number, b: number) {
    return a + b;
}
var sum = add(5, 3);
alert(sum);


var multiply: IMath;
multiply = function (a: number) {
    return a;
}
var result = multiply(5, 3);
alert(result);

Similar to add function, we have declared multiply however we have passed only one parameter and still it works as function types interface declaration cares about only the return type of the function. As long as return type is number, TypeScript type-checker doesn't have any problem.

The JavaScript output of the above TypeScript code is below.

JavaScript output

// using the interface
var add;
add = function (a, b) {
    return a + b;
};
var sum = add(5, 3);
alert(sum);
var multiply;
multiply = function (a) {
    return a;
};
var result = multiply(5, 3);
alert(result);

It is little confusing why multiply function should work, because the declaration accepts only one parameter but while calling we are calling with two parameters.

This is because how the JavaScript works. JavaScript makes a best guess of the function name and parameters. If the function name matches it calls that function with matched parameters values and if a parameter is missing that is ignored. Read more discussion about it here.

 Views: 9904 | Post Order: 3



Write for us






Hosting Recommendations