0

I'm trying to use generics in backbone typescript definition. Why does the following code not work?! Try it in the playground.

declare module Backbone {
    class Model{}

    interface ViewOptions<TModel extends Model> {
        model?: TModel;
    }

    class View<TModel extends Model> {
        constructor(options?: ViewOptions<TModel>);
        model: TModel;
    }
}

class MyModel extends Backbone.Model {
}

class MyView extends Backbone.View<MyModel> {
}

// Error: Could not select overload for 'new'' expression.
var myView = new MyView({ model: new MyModel(), num: 1 });

// In typescript playground when you hover on 'model' in
// previous line it correctly shows its type as 'MyModel'

var model = myView.model; // expected to be of type MyModel

Update:

I figured the compiler will pass if I explicitly set the constructor for MyView:

class MyView extends Backbone.View<MyModel> {
    constructor(options?: Backbone.ViewOptions<MyModel>) {
        super();
    }
}

But then what is the use of generics?! Is this a defect in the compiler?!

4

1 回答 1

1

If you do not specify your constructor the compiler expects TModel and not MyModel which is what you are trying to pass in. Seems like a compiler bug Your understanding of generics is correct.

Additionally be sure to pass over the parameter to the super class :

class MyView extends Backbone.View<MyModel> {
     constructor(options?: Backbone.ViewOptions<MyModel>) {
        super(options); // Pass this on 
    }
}
于 2013-08-08T07:09:37.557 回答