Method format within Angular2 model class

2019-07-11 14:04发布

问题:

I have a basic model class (not a component):

export class catModel { 
 constructor(public name: string) { }
 getName: string {
  return this.name.toUpperCase();
 }
}

Now I'll try and use this model in a component like this:

feline: catModel = {name: 'simba' };

...when I compile I get the following error:

Type '{ name: string }' is not assignable to type 'catModel'. Property 'getName' is missing in type '{ name: string }'

As soon as remove the getName function from the catModel it works fine, why won't it let me add a method?

回答1:

It's because Typescript uses a structural type system. As stated in the TypeScript docs: Type Compatibility

The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x

"same members" means properties and methods. If you think about this reasoning, it makes perfect sense. By typing something as CarModel, you are making a guarantee to anyone using it that it will behave like a CarModel. If you don't have a getName in your object literal, then it can't be a CarModel, as it doesn't follow the contract.

Read the second link above. It's a great reference document.


Probably not what the main concern in your post is about, but the obvious solution is to just construct an instance of the class new CarModel('simba').



回答2:

This should resolve your problem,

export class catModel { 

  name:string;    //<-----here

  constructor(public name: string) { }

  getName: string {
    return this.name.toUpperCase();
  }

}