Skip to content Skip to sidebar Skip to footer

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 = {

Solution 1:

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.

classHero { id: number; name: string }

or

interfaceHero { 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.

Solution 2:

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:

let hero: Hero = { ID: 1, Name: 'goku'};

but if you want to instantiate with the constructor you can do this in the class

classHero
{
    //notice optional parameters. You have more flexibility this way.constructor(id?: number, name?: string)
    {  
      this.ID = id;
      this.Name = name;
    }

    ID: number;
    Name: string
}

And do this with the implementation

let hero: Hero = new Hero(1,'goku');
let hero2: Hero = { ID: 2, Name: 'superman' }

Post a Comment for "Typescript, Using Classes Without Constructor"