Skip to content

Instantly share code, notes, and snippets.

@alpicola
Created September 2, 2014 07:14
Show Gist options
  • Save alpicola/79115fb60c4c109b716d to your computer and use it in GitHub Desktop.
Save alpicola/79115fb60c4c109b716d to your computer and use it in GitHub Desktop.
// inspired: http://journal.stuffwithstuff.com/2013/04/23/playing-with-generics-in-typescript-0.9.0/
class Base {
foo() : void {}
}
// If `Derived' has no addional method, we'll get different results
class Derived extends Base {
bar() : void {}
}
var a : Base = new Derived();
var b : Derived = new Base(); // error
class Box<T> {
constructor(public value:T) {}
};
// Covariance
var c : Box<Base> = new Box<Derived>(null);
var d : Box<Derived> = new Box<Base>(null); // error
var e : () => Base = () => { return new Derived };
var f : () => Derived = () => { return new Base }; // error
// Function argument bivariance
var g : (x:Base) => void = (x:Derived) => { x.bar() }; // no error, but `g(new Base)' causes a runtime error!
var h : (x:Derived) => void = (x:Base) => {};
// Extra parameter subtyping
var i : (x:Base, y:number) => void = (arg:Base) => {};
var j : (x:Base) => void = (arg:Base, additional:number) => {}; // error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment