Reputation: 3897
I'm trying to use Backbone with Typescript, and I'm not following Typescript's syntax for how to define which type of model a collection will hold.
module Application.Collections {
export class Library extends Backbone.Collection {
model = Application.Models.Book; // THIS LINE DOESN'T WORK
constructor(options?) {
super(options);
};
}
}
module Application.Models {
export class Bookextends Backbone.Model {
constructor(options?) {
super(options);
}
}
}
The error I get is:
Type of overridden member 'model' is not subtype of original
member defined by type 'Collection';
It's also not clear to me when I should put definitions like this in the constructor, or whether it matters. I tried:
constructor(options?) {
super(options);
this.model = Application.Models.Entity;
};
Which says:
Cannot convert 'new(options?:any) => Models.Template' to 'Backbone.Model'
What I'm really trying to do is define a model type that has a few utility methods - when the basic model data is fetched from the server, I want the model to initialize and calculate a few convenience properties based on the server data. But this isn't happening, because the collection.fetch() doesn't think the return model is of any specific type.
Upvotes: 2
Views: 1385
Reputation: 94
Declare the model before "super(options);"
module Application.Models {
export class Book extends Backbone.Model {
constructor(options?) {
super(options);
}
}
module Application.Collections {
export class Library extends Backbone.Collection {
constructor(options?) {
this.model = Application.Models.Book;
super(options);
};
}
}
Upvotes: 2
Reputation: 251072
If you want to type that variable, you would use:
model: Application.Models.Book;
If you want the class name at runtime, you can either use a string, or this method of obtaining the class name at runtime.
model = 'Application.Models.Book';
Or
model = Describer.getName(someObject);
There is a limit on this second method that you only get the class name, not the full path.
Upvotes: 1