Angular: Interfaces

Interfaces can be used to ensure that an object has certain properties. For example:

interface Weapon {
  name: string;
  type: string
}

We can then say:

let myWeapon: Weapon;
myWeapon = {
  name: 'Sword of Shadow',
  type: 'greatsword'
}

If we try to assign an object that doesn’t have all the properties of Weapon, we get an error:

myWeapon = {
  name: 'Sireth, Spear of the Sky';
}
// ^ That will cause an error, because the property 'type' is missing

We can make any property of an interface optional with the ? operator:

interface Ring {
  name: string;
  type?: string
}
let myRing: Ring;
myRing = {
  name: 'Stolen Signet of ir'Wynarn';
}
// ^ This will work, because the property 'type' is optional in the Ring interface