Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 26, 2018 13:20
Show Gist options
  • Save ivankisyov/6601027fb5613ac8a3591098a18eaab6 to your computer and use it in GitHub Desktop.
Save ivankisyov/6601027fb5613ac8a3591098a18eaab6 to your computer and use it in GitHub Desktop.
Interfaces in TypeScript

Interfaces in TypeScript

interface User {
  membership: string;
  active: boolean;
  status?: boolean; // optional prop
  [propName: string]: any; // not aware of the names of the rest of the props
}

function setMembership(user: User, type: string): string {
  user.membership = type;
  return `User membership is ${user.membership}`;
}

const profile = {
  membership: "standard",
  active: true,
  memberSince: "2015"
};

const newMembership = setMembership(profile, "premium");
console.log(newMembership);

Classes and Interfaces

interface PersonInterface {
  firstName: string;
  lastName: string;
  active: boolean;
  getStatus(): boolean;
}

class Person implements PersonInterface {
  public active = true;
  constructor(public firstName: string, public lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getStatus() {
    return this.active;
  }
}

const smith = new Person("john", "smith");
console.log(smith);
console.log(smith.getStatus());

Functions and Interfaces

interface SquareFuncInterface {
  (num: number): number;
}

let squareFunc: SquareFuncInterface = number => number * number;

squareFunc(11);

Interface inheritance

interface Person {
  firstName: string;
  lastName: string;
}

interface MalePerson extends Person {
  gender: string;
}

// error: missing properties
const smith: MalePerson = {
  gender: "male"
};

// error-free
const jimmy: MalePerson = {
  gender: "male",
  firstName: "Jimmy",
  lastName: "Smith"
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment