Resources

Choosing one

Type aliases and interfaces are very similar.

Type has more features, but most of their features are the same.

The key distinction is:

  • A type cannot be re-opened to add new properties.
  • An interface which is always extendable.

Which one to use? The docs say you can choose based on personal preference and the compiler will tell you if it needs something else. And gives a recommendation to you use interface (with fewer feature), until you need to use a feature specific to type.

Extending

Extend an interface

interface Animal {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

const bear = getBear()
bear.name
bear.honey

Extend a type via intersections

type Animal = {
  name: string
}

type Bear = Animal & {
  honey: Boolean
}

const bear = getBear()
bear.name
bear.honey

Combine two types.

type Name = {
  name: "string"
};

type Age = {
  age: number
};

type Person = Name & Age;

Combine two interfaces. You canโ€™t reverse this as an interface made of two types.

interface Name {
  name: "string"
};

interface Age {
  age: number
};

type Person = Name & Age;

Adding fields

Declare an interface multiple types and they will all be collapsed into one.

interface Window {
  title: string
}

interface Window {
  ts: import("typescript")
}

const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});

You get an error if you do that with types.

// Error: Duplicate identifier 'Window'.