Typescript: Can't instantiate object using object literals when a function exists in the class

angular, typescript2.0

Solution

Your instantiation is wrong. Either call the constructor with new

person: Person = new Person()

Or create a complete object literal

person: Person = {
    id: 1,
    name: "Jack Johnson",
    height: 180,
    weight: 70,
    calculateBmi: function() {...}
  };

Problem

I just started playing with Angular 2 and Typescript, and recently came across some behaviour I find quite strange. My class looks like this: ``` export class Person{ id: number; name: string; height: number; weight: number; calculateBmi() { return (weight/(height*height)); } } ``` When instantiating a new person using object literals, like this: ``` person: Person = { id: 1, name: "Jack Johnson", height: 180, weight: 70 }; ``` I get a (design time) error in Visual Studio 2017 saying: Type '{id: number, name: string, height: number, weight: number}' is not assignable to type 'Person' Property 'calculateBmi' is missing in type '{id: number, name: string, height: number, weight: number}' It also states that it Cannot convert type '{id: number, name: string, height: number, weight: number}' to type 'Person': Type 'Person' has non-optional property 'calculateBmi' which is not present in type '{id: number, name: string, height: number, weight: number}'. So it seems that the transpiler regards 'calculateBmi' as a property, not a function. The work around is of course to add a constructor and use that to instantiate the class, but I'd like to learn if there is any way to solve this so I could still use object literals? Thanx, Jon BTW.: I'm using Resharper 2017.x but I don't this this is what's causing the error message to appear.

Original source