Angular2 模型中的方法格式 class
Method format within Angular2 model class
我有一个基本模型class(不是组件):
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 函数就可以正常工作,为什么它不让我添加方法?
这应该可以解决您的问题,
export class catModel {
name:string; //<-----here
constructor(public name: string) { }
getName: string {
return this.name.toUpperCase();
}
}
这是因为 Typescript 使用了 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" 表示属性 和 方法。如果你考虑这个推理,它是完全有道理的。通过键入 CarModel
,您向任何使用它的人保证它的行为类似于 CarModel
。如果您的对象字面量中没有 getName
,那么它 不能 是 CarModel
,因为它不符合约定。
阅读上面的第二个 link。这是一个很好的参考文档。
可能不是您 post 中的主要关注点,但显而易见的解决方案是构建 class new CarModel('simba')
的实例。
我有一个基本模型class(不是组件):
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 函数就可以正常工作,为什么它不让我添加方法?
这应该可以解决您的问题,
export class catModel {
name:string; //<-----here
constructor(public name: string) { }
getName: string {
return this.name.toUpperCase();
}
}
这是因为 Typescript 使用了 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 withy
ify
has at least the same members asx
"same members" 表示属性 和 方法。如果你考虑这个推理,它是完全有道理的。通过键入 CarModel
,您向任何使用它的人保证它的行为类似于 CarModel
。如果您的对象字面量中没有 getName
,那么它 不能 是 CarModel
,因为它不符合约定。
阅读上面的第二个 link。这是一个很好的参考文档。
可能不是您 post 中的主要关注点,但显而易见的解决方案是构建 class new CarModel('simba')
的实例。