neemspees/tragic-methods

Suggestion: TypeScript generic types are covariant

pedropedruzzi opened this issue · 3 comments

Hi. I love this repo!

I created this gist to show the issues of TypeScript generic types being covariant: https://gist.github.com/pedropedruzzi/30612deae94b2e840fb2faeb7443e106

I don't have time to put together a PR adding this to the right format. But if anybody wants to, feel free to use my code as you wish.

Thanks.

@pedropedruzzi, thanks for this interesting quirk!

Thanks for adding it! Note: this is not only for arrays. Every generic type in TypeScript is covariant. For example:

interface Reference<T> {
    value?: T;
}

function testInterface() {
    const circleRef: Reference<Circle> = {};
    const shapeRef: Reference<Shape> = circleRef; // ISSUE: should be syntax error: Type 'Reference<Circle>' is not assignable to type 'Reference<Shape>'
    const square: Square = { name: 'square of length 10', length: 10 };
    const shape: Shape = square;

    shapeRef.value = shape; // allowed because shapeRef is a Reference<Shape> in compile time
    shapeRef.value = square; // same

    const circle: Circle | undefined = circleRef.value; // this is a Square not a Circle!

    return circle;
}

@pedropedruzzi, thanks, it has been updated.