Angular2模型类中的方法格式 [英] Method format within Angular2 model class

查看:73
本文介绍了Angular2模型类中的方法格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的模型类(不是组件):

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:

类型'{{name:string}'不可分配给类型'catModel'.类型'{名称:字符串}'中缺少属性'getName'

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

一旦从catModel中删除getName函数,它就可以正常工作,为什么不让我添加一个方法呢?

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

推荐答案

这是因为Typescript使用结构类型系统.如 TypeScript文档:类型兼容性

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

TypeScript的结构类型系统的基本规则是,如果y至少具有与x

相同成员"表示属性方法.如果您考虑这种推理,那将是非常合理的.通过将某些内容键入CarModel,您可以保证使用它的任何人都可以像CarModel一样操作.如果您的对象字面量中没有getName,则它不能CarModel,因为它不遵守合同.

"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.

可能不是您的帖子中主要关注的内容,但是显而易见的解决方案是仅构造类new CarModel('simba')的实例.

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

这篇关于Angular2模型类中的方法格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆