When it comes to using class as a type, the distinction between whether something is an interface or a class becomes irrelevant. In the example provided, whether Hero is defined as an interface or a class, it serves as a type for the variable.
class Hero { id: number; name: string }
Alternatively, it can be declared as:
interface Hero { id: number; name: string }
The crucial point is that whether Hero is a class or an interface doesn't impact its usage as a type:
let hero: Hero = { id: 1, name: 'me' }
The key difference between an interface
and a class
lies in the fact that an interface
is merely for development purposes and doesn't get converted into JavaScript. On the other hand, a class
does get transpiled, and you are unable to create a new instance of an interface
.
Whether there is a constructor present or not, if you use new
to create an object instance, it will be considered an instanceof
that class. This can be demonstrated by:
let hero = new Hero();
Executing a log of instanceof
will return true
because you have successfully instantiated an object of the Hero class using the keyword new
.