TypeScript types

by Bernat Comerma

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  text-align: center;
}

TypeScript

let myFavoritePet: "dog";
myFavoritePet = "dog";
// Error: Type '"rock"' is not assignable to type '"dog"'.
// myFavoritePet = "rock";
type Species = "cat" | "dog" | "bird";
interface Pet {
  species: Species;
  name: string;
  eat(): void;
  walk(): void;
  sleep(): void;
}
interface Cat extends Pet {
  species: "cat";
}
interface Dog extends Pet {
  species: "dog";
}
interface Bird extends Pet {
  species: "bird";
  sing(): void;
}
// Error: Interface 'Rock' incorrectly extends interface 'Pet'. Types of property 'species' are
// incompatible. Type '"rock"' is not assignable to type '"cat" | "dog" | "bird"'. Type '"rock"' is not
// assignable to type '"bird"'.
// interface Rock extends Pet {
// type: "rock";
// }
function buyPet(pet: Species, name: string): Pet;
function buyPet(pet: "cat", name: string): Cat;
function buyPet(pet: "dog", name: string): Dog;
function buyPet(pet: "bird", name: string): Bird;
function buyPet(pet: Species, name: string): Pet {
  if (pet === "cat") {
    return {
      species: "cat",
      name: name,
      eat: function() {
        console.log(`${this.name} eats.`);
      },
      walk: function() {
        console.log(`${this.name} walks.`);
      },
      sleep: function() {
        console.log(`${this.name} sleeps.`);
      }
    } as Cat;
  } else if (pet === "dog") {
    return {
      species: "dog",
      name: name,
      eat: function() {
        console.log(`${this.name} eats.`);
      },
      walk: function() {
        console.log(`${this.name} walks.`);
      },
      sleep: function() {
        console.log(`${this.name} sleeps.`);
      }
    } as Dog;
  } else if (pet === "bird") {
    return {
      species: "bird",
      name: name,
      eat: function() {
        console.log(`${this.name} eats.`);
      },
      walk: function() {
        console.log(`${this.name} walks.`);
      },
      sleep: function() {
        console.log(`${this.name} sleeps.`);
      },
      sing: function() {
       ...