Skip to content

Instantly share code, notes, and snippets.

@pedropedruzzi
Created February 2, 2022 17:47
Show Gist options
  • Save pedropedruzzi/30612deae94b2e840fb2faeb7443e106 to your computer and use it in GitHub Desktop.
Save pedropedruzzi/30612deae94b2e840fb2faeb7443e106 to your computer and use it in GitHub Desktop.
Generic Type Bug in TypeScript
interface Shape {
name: string;
}
interface Square extends Shape {
length: number;
}
interface Circle extends Shape {
radius: number;
}
function test() {
const circles: Circle[] = [];
const shapes: Shape[] = circles; // ISSUE: should be syntax error: Type 'Circle[]' is not assignable to type 'Shape[]'
const square: Square = { name: 'square of length 10', length: 10 };
const shape: Shape = square;
shapes.push(shape); // allowed because shapes is a Shape[] in compile time
shapes.push(square); // same
const firstCircle: Circle = circles[0]; // this is not a Circle!
return firstCircle;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment