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
interfaceIClassyAnimal{new(name:string):IAnimal;}
that is not an interface you should implement. That's a type to describe the class itself. For example:
classParrot{constructor(publicname:string){}}functionpetFactory(petClass:IClassyAnimal,name:string){returnnewpetClass(name);}constpet=petFactory(Parrot,'McParrotface');// this is fine
This means that if you have static properties defined on a class, you can have them defined on an interface:
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 Parrotinstances comply to the shape defined by IAnimal.
Edit: missed one of your replies in the comments that is actually on point on that 🙂
type
s are actually aliasesOne 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 oftype
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 signaturesMy suggestion here is that you're misunderstanding the role of interface that define constructor signatures. When you do
that is not an interface you should implement. That's a type to describe the class itself. For example:
This means that if you have static properties defined on a class, you can have them defined on an interface:
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 writeclass Parrot implements IAnimal {...}
, becauseParrot
instances comply to the shape defined byIAnimal
.Edit: missed one of your replies in the comments that is actually on point on that 🙂
this is interesting. I saw it somewhere before but didn't pay attention, now I see what this was about.