Interfaces in TypeScript

The interface defines the contract of an application. It defines the structure for classes to follow. Classes that implement an interface must follow the structure declared in the interface.

Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. The implementing class is responsible to define the members.

Example of interface

  interface IUser {
    firstName:string,
    lastName:string,
    getName: () => string
  }

  const student: IUser = {
    firstName: 'Joe',
    lastName: 'Smith',
    getName: ():string => student.firstName + student.lastName
  };

  console.log(student.getName());

In the above example, if we miss one property on student object then it will throw an error. Please check the following code segment:

const student: IUser = {
   lastName: 'Smith',
   getName: ():string => student.firstName + student.lastName
}

// Error: Property 'firstName' is missing in type '{ lastName: string; getName: () => string; }' but required in type 'IUser'.
Interfaces are just part of TypeScript. It has zero runtime JavaScript impact.

Interfaces with union types

We can define an interface with union-type attributes. See the code below:

  interface IUser {
    userId: number|string, // union type
    firstName:string,
    lastName:string,
    getName: () => string
  }

Interfaces and Inheritance

  interface IUser {
    userId: number|string,
    firstName:string,
    lastName:string,
    getName: () => string
  }

  interface IEmployee extends IUser {
    department: string,
  }

  const manager: IEmployee = {
    userId: 2333,
    firstName: 'Joe',
    lastName: 'Smith',
    department: 'HR',
    getName: ():string => manager.firstName + manager.lastName
  };

  console.log(manager.getName());