Last active
October 5, 2017 02:37
-
-
Save third774/dadd8e0fb2ca3238b60ff61dbd97d985 to your computer and use it in GitHub Desktop.
Typescript generic problems and fixes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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