Typescript, using classes without constructor

2020-02-24 16:39发布

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) {}
}

2条回答
Melony?
2楼-- · 2020-02-24 17:16

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.

查看更多
祖国的老花朵
3楼-- · 2020-02-24 17:35

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

class Hero
{
    //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' }
查看更多
登录 后发表回答