lavrton
lavrton

Reputation: 20323

How to properly define backbone collection using typescript?

I am using backbone.d.ts from https://github.com/borisyankov/DefinitelyTyped/.

Typescript version 0.9.1

Problem: I can't properly define Backbone.Collection:

Code:

   /// <reference path='./backbone/backbone.d.ts'/>

   import Backbone = require("backbone");

   class User extends Backbone.Model {
        getName() : string {
        return "User Name";
        }
   }

   class Users extends Backbone.Collection {
        model = User;
   }

   var users = new Users();

   var firstUser = users.create({});
   console.log(firstUser.getName());

Trying to compile: tsc ./users.ts -m amd And I got the error:

error TS2094: The property 'getName' does not exist on value of type 'Backbone.Model'.

How to solve this problem?

Upvotes: 0

Views: 1739

Answers (1)

lavrton
lavrton

Reputation: 20323

You can use generics here : http://blogs.msdn.com/b/typescript/archive/2013/03/25/working-on-typescript-0-9-generics-overload-on-constants-and-compiler-performance.aspx

It is possible to rewrite definition file with using generics: https://gist.github.com/lavrton/7226521

Then every time you are creating backbone collection you must include the model:

var users = new Backbone.Collection<User>();

or better and cleaner:

class Users extends Backbone.Collection<User> {
   model = User;
}
var users = new Users();

Now typescript will give your right model type on every collection methods. You can do same things for Backbone.View.

Offtopic tip: Also it is better to write model property to prototype:

class Users extends Backbone.Collection<User> {
}
Users.prototype.model = User;

Upvotes: 1

Related Questions