DEV Community

Discussion on: TypeScript: type vs interface

Collapse
 
maxart2501 profile image
Massimo Artizzu • Edited

types are actually aliases

One of the sudden realizations I had about types and interfaces in TypeScript is that they're not actually "types", they're type aliases. As they don't define new types, they just they give them a new name.

In other words, they could have used the keyword alias instead of type and maybe saved some troubles.

This means that interfaces are "opaque" relatively to its internal structure, whereas type aliases are not. I.e., the type hint you get is just interface IAnimal in the former case, and the whole type alias definition in the latter.

Using new to define constructor signatures

My suggestion here is that you're misunderstanding the role of interface that define constructor signatures. When you do

interface IClassyAnimal {
  new (name: string): IAnimal;
}
Enter fullscreen mode Exit fullscreen mode

that is not an interface you should implement. That's a type to describe the class itself. For example:

class Parrot {
  constructor(public name: string) {}
}

function petFactory(petClass: IClassyAnimal, name: string) {
  return new petClass(name);
}
const pet = petFactory(Parrot, 'McParrotface'); // this is fine
Enter fullscreen mode Exit fullscreen mode

This means that if you have static properties defined on a class, you can have them defined on an interface:

interface IClassyAnimal {
  new (name: string): IAnimal;
  group: string;
}
const petClass: IClassyAnimal = class Parrot {
  static group = 'Bird';
  constructor(public name: string) {}
}
Enter fullscreen mode Exit fullscreen mode

On the other hand, when you're using implements in a class, you're describing the shape of an instance of that class. Which means you write class Parrot implements IAnimal {...}, because Parrot instances comply to the shape defined by IAnimal.

Edit: missed one of your replies in the comments that is actually on point on that 🙂

Collapse
 
stereobooster profile image
stereobooster • Edited

the type hint you get is just interface IAnimal in the former case, and the whole type alias definition in the latter.

this is interesting. I saw it somewhere before but didn't pay attention, now I see what this was about.