2013-10-30 57 views
0

我正在使用來自https://github.com/borisyankov/DefinitelyTyped/的backbone.d.ts。如何正確定義使用打字稿的骨幹收集?

打字稿版本0.9.1

問題:我無法正確定義Backbone.Collection:

代碼:

/// <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()); 

試圖編譯:tsc ./users.ts -m amd 我得到了錯誤:

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

如何解決t他的問題?

回答

1

你可以在這裏使用泛型:http://blogs.msdn.com/b/typescript/archive/2013/03/25/working-on-typescript-0-9-generics-overload-on-constants-and-compiler-performance.aspx

有可能改寫定義文件中使用泛型: https://gist.github.com/lavrton/7226521

然後每次創建骨幹收集時間,你必須包括模型:

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

或更好,更清潔:

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

現在打字稿將爲您的每種收集方法提供正確的模型類型。 你可以爲Backbone.View做同樣的事情。

Offtopic提示: 也最好是模型屬性寫入原型:

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

甚至比使用原型更好的是創造一個getter: 領型(){ 回報用戶; } – noname

+0

@noname好方法。看起來更好! – lavrton