Reputation: 164139
I've created a short sample code to demonstrate the problem I'm facing:
class List<T> { }
class StringList extends List<string> { }
class NumberList extends List<number> { }
class Iterator<T extends List<any>> {
list: T;
constructor() {
this.list = new StringList();
}
}
This code results in Cannot convert 'StringList' to 'T'
.
Any idea why and how to avoid it? Thanks.
Here's an example of why it's wrong (thanks to @RyanCavanaugh for pointing it out):
var iterator: Iterator<List<any>> = new Iterator<NumberList>();
Where you'd expect iterator
to have list of type List<number>
but the ctor tried to assign List<string>
to it.
Upvotes: 0
Views: 341
Reputation: 220964
This is an error because it's wrong:
class MagicList extends StringList {
magic = 'shazam';
}
var x = new Iterator<MagicList>();
console.log(x.list.magic); // x.list does not have member 'magic'
Remember that a constraint only establishes a lower bound on the generic type.
Upvotes: 2