Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript, using classes without constructor

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) {} } 
like image 844
Kevin Koshka Avatar asked Dec 27 '17 17:12

Kevin Koshka


People also ask

Do TypeScript classes need constructor?

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.

How do you use a class in TypeScript?

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.

Should you use classes in TypeScript?

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.

Why do we use constructor in TypeScript?

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.


1 Answers

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.

like image 52
lock42 Avatar answered Sep 27 '22 22:09

lock42