0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well yeah, it's pretty obvious ha? Now I feel retarded. Your example wasn't dead on (for one thing you did not put magic on the list member, just added a member, so you have x.magic) but I got the point and edited my question with an example. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.