2016-09-11 18 views
2

我有一个基本的模型类(而不是组件):方法格式

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

现在,我会试着在这样的组件使用这个模型:

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

...当我编译我得到以下错误:

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

只要从catModel中删除getName函数它工作正常,wh你不会让我添加一个方法吗?

回答

3

这是因为打字稿使用structural type system。正如在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

“相同的部件” 表示是指性质方法。如果你考虑这个推理,这是非常有意义的。通过输入CarModel之类的东西,您可以向任何使用它的人保证其行为如同CarModel。如果您的对象字面上没有getName,那么它不会不能CarModel,因为它不遵循合同。

阅读上面的第二个链接。这是一份很棒的参考文件。


也许不是在您的文章主要关注的是什么,但显而易见的解决方法就是构建类new CarModel('simba')的一个实例。

+0

这样做,使用'新'解决了这个问题。 – Helzgate

0

这应该解决您的问题,

export class catModel { 

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

    constructor(public name: string) { } 

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

}