While working with the "Tour of Heroes" tutorial on the Angular website I found the following syntax (shortly):
class Hero { id: number, name: string, } const aHero: Hero = { id: 1, name: 'Superman' } console.log(aHero instanceof Hero); //false
What would be the point in doing this? when if I check the type of "aHero", it is only a common object and not a "Hero" type. Would it be better just initializing an object with a constructor?:
class Hero { constructor(id: number, name: string) {} }
Classes in TypeScript do not require you to explicitly write a constructor. However if you are extending a base class you will need to create a constructor to call super() at a minimum.
You can do this by using the new keyword, followed by a syntax similar to that of an arrow function, where the parameter list contains the parameters expected by the constructor and the return type is the class instance this constructor returns. The TypeScript compiler now will correctly compile your code.
When should we use classes and interfaces? If you want to create and pass a type-checked class object, you should use TypeScript classes. If you need to work without creating an object, an interface is best for you.
A constructor is a special function of the class that is responsible for initializing the variables of the class. TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class.
You can use class as a type which is the way you're using it. So, whether Hero is an interface or class it doesn't matter because you're using it as a type.
class Hero { id: number; name: string }
or
interface Hero { id: number; name: string }
The following doesn't concern whether Hero is a class or interface
let hero: Hero = { id: 1, name: 'me' }
Where interface
and class
differentiate is interface
is only for you, it doesn't get transpiled into javascript. A class
does and you cannot new
an interface
.
Constructor or no Constructor, if you new
it then it is an instanceof
. Try it again with this
let hero = new Hero();
Your instanceof
log will be true
because you did create an instance of Hero with the key word new
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With