Nitzan Tomer
Nitzan Tomer

Reputation: 164139

Error with generics in type constraint in TypeScript

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

(on playground)

This code results in Cannot convert 'StringList' to 'T'.

Any idea why and how to avoid it? Thanks.


Edit

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

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

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

Related Questions