Skip to content

Instantly share code, notes, and snippets.

@undeadcat
Created September 23, 2017 00:03
Show Gist options
  • Save undeadcat/ac53178d4bd15a960f36c2fa2a7a95f2 to your computer and use it in GitHub Desktop.
Save undeadcat/ac53178d4bd15a960f36c2fa2a7a95f2 to your computer and use it in GitHub Desktop.
TypeScript is unsound
class Base {
}
class Derived extends Base {
y:string
}
//pretend we have variance
class Collection1<T>{
accept(value: T) { }
}
var derivedCollection: Collection1<Derived> = new Collection1<Base>();
derivedCollection.accept(new Derived())
class Collection2<T>{
getResult(): T { return null }
}
var baseCollection2: Collection2<Base> = new Collection2<Derived>();
var result: Base = baseCollection2.getResult()
//but adding an indexer breaks everything
class Base {
}
class Derived extends Base {
y: string
}
class Collection3<T>{
["string"]: T;
}
var derived: Collection3<Derived>
derived["foo"] = new Base();
var base: Collection3<Base>
derived["foo"] = new Derived();
//unsound
var original = new Map<string, Derived>();
var viaBase: Map<string, Base> = original;
var viaDerived: Map<string, Derived> = original;
viaBase["fff"] = new Base();
console.log(viaDerived["fff"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment