Suggestion: TypeScript generic types are covariant
pedropedruzzi opened this issue · 3 comments
pedropedruzzi commented
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.
neemspees commented
@pedropedruzzi, thanks for this interesting quirk!
pedropedruzzi commented
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;
}
neemspees commented
@pedropedruzzi, thanks, it has been updated.