Interfaces in TypeScript

Handbook

Overview

Interface in TypeScripts are used to create a blueprint or an abstraction of a class.

An interface can contains properties (mandatory, optional or readonly)

interface Example {
  mandatory: string;
  optional?: string;
  readonly ro: string;
}

And methods

interface Example {
  mandatory: string;
  optional?: string;

  concat(sep: string): string;
}

To use the interface, a class should implement it,

class Impl implements Example {
  mandatory: string;
  optional?: string;

  constructor(m: string, o: string) {
    this.mandatory = m;
    this.optional = o;
  }

  contact(sep: string): string {
    return `${this.mandatory}${sep}${this.optional}`;
  }
}

The Promise case

What about a promise based method ? Do not forget what async/await does. It wraps all the things in Promise<T>.

In order to add promise to your interface, just specify a Promise as return type.

interface Example {
  mandatory: string;
  optional?: string;

  promize(arg: string): Promise<string>;
}