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) {}
}
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.
or
The following doesn't concern whether Hero is a class or interface
Where
interface
andclass
differentiate isinterface
is only for you, it doesn't get transpiled into javascript. Aclass
does and you cannotnew
aninterface
.Constructor or no Constructor, if you
new
it then it is aninstanceof
. Try it again with thisYour
instanceof
log will betrue
because you did create an instance of Hero with the key wordnew
.I know this question has been answered before but as far as object oriented code goes it was always like this.
I believe you can do this without a constructor:
but if you want to instantiate with the constructor you can do this in the class
And do this with the implementation