Skip to content

Instantly share code, notes, and snippets.

@third774
Last active October 5, 2017 02:37
Show Gist options
  • Save third774/dadd8e0fb2ca3238b60ff61dbd97d985 to your computer and use it in GitHub Desktop.
Save third774/dadd8e0fb2ca3238b60ff61dbd97d985 to your computer and use it in GitHub Desktop.
Typescript generic problems and fixes
class Animal {
name: string;
}
class Dog extends Animal {
bark() {};
}
class Cat extends Animal {
meow() {};
}
class Box<V> {
item: V;
}
// function f<T extends Box<Animal>>(box: T): T {
function f<T extends Box<Animal>>(box: T): Box<Animal> { // specify return type as Box<Animal> to expand generic return type
box.item = new Cat(); // <-- This is perfectly valid and allowed by the constraint
return box; // <-- The returned type is T
}
let result = f(new Box<Dog>()); // Type of 'result' is inferred as Box<Dog>
// Now error is thrown as expected
result.item.bark(); // <-- No compilation error. Run-time error...
let cats: Cat[] = [];
// let animals: Animal[] = cats;
let animals = cats;
// remove explicit type declaration and error is thrown
animals.push(new Dog())
cats.forEach(cat => cat.meow()) // <-- No compilation error. Run-time error...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment