Interface

  • Defines a “shape” for JavaScript objects, functions and more

  • Creates a contract for code

Little Background

Blueprint for an object (loosely)

function printMe(obj){
    console.log(obj.name);
}

printMe({ name: "Kamal" }); // Kamal
printMe({ age: 20 }); // undefined

// solution to above problem
interface person{
    name: string;
    age?: Number; //  optional
}

function printMe(obj: person){
    console.log(obj.name, obj.age || 12);
}

printMe({ name: "Kamal" });

Basic Interfaces

Basic interfaces in TypeScript are for the type Object

Optional Properties

Interfaces can have optional properties

Function types

Interfaces can describe Functions as well

Array Types

  • Interface can define both the kind of key an array uses and the type of entry it contains

  • Index can be of type string or type number

Class Types

  • Interfaces can define a class similar to Java

Extending Interfaces

Interfaces can extend other interfaces

Hybrid Interfaces

TypeScript interfaces can describe something that is a function and an object at the same time. Because, JavaScript!

Last updated

Was this helpful?