简体   繁体   中英

Method format within Angular2 model class

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?

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') .

This should resolve your problem,

export class catModel { 

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

  constructor(public name: string) { }

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM