user2502794
user2502794

Reputation: 137

Typescript Method TS2322 error

I am able to create an Typescript class object, however every time I create any method on the class it breaks.

export class VacationServerResults {

 vacationOffers: Array<VacationHotelTicketDateOffersModel>;


constructor() {
    this.vacationOffers = new Array<VacationHotelTicketDateOffersModel>();

}

public greet() {
    return "hello";
}   

}

Everytime I add the greet method, I get the following error.

file: 'file: severity: 'Error' message: 'Type '{ "vacationOffers": { "vacationOffer": { "offerType": string; "hotelRoomBasePrice": number; "hote...' is not assignable to type 'VacationServerResults'.
Property 'greet' is missing in type '{ "vacationOffers": { "vacationOffer": { "offerType": string; "hotelRoomBasePrice": number; "hote...'.' at: '36,5' source: 'ts'

Upvotes: 1

Views: 862

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249656

You probably have another place in your code where you assign an object literal to an object of type VacationServerResults. Typescript uses structural compatibility to determine type compatibility, so the following code is valid:

class Dog {
  name: string;
}

var d: Dog = {name : "My dog"};

Once you add a method the object literal will no longer satisfy the structure of the class and we get your error. You could do one of the following:

Assign the method in the object literal (a rather hack-ish solution)

class Dog {
  name: string;
  bark(): void{}
}

var d: Dog = {name : "My dog", bark: Dog.prototype.bark };

Create a constructor for your class that takes the object literal and new-up your objects instead of using object literals:

class Dog {
  constructor(props: { name: string }){
    Object.assign(this, props)
  }
  name: string;
  bark(): void{}
}

var d = new Dog({name : "My dog" });

Upvotes: 1

Related Questions