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?
This should resolve your problem,
It's because Typescript uses a structural type system. As stated in the TypeScript docs: Type Compatibility
"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 aCarModel
. If you don't have agetName
in your object literal, then it can't be aCarModel
, 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')
.