Closed
Description
This proposal serves, at this point, as an trial-and-error experience for myself and to give you guys some ideas to play with.. I understand this may not be 'it' in current form (or not at all) so don't just stamp it with that dreaded "DECLINED" thing. I'll just close it myself after you explain to me how bad it is and why.. and all the edge cases..(e.g. expressions in extends clauses etc.) or who knows, I may be even able to fix it later..
Let A
and B
be two classes and a: A
, b: B
.
For the structurally valid assignment a = b
.
Either one of the following conditions should hold to error:
B
is a strict nominal ancestor ofA
.A
is a nominal ancestor ofB
but with an incompatible generic signature.
Examples:
class Base {
action = "START WORLD WAR III";
}
class Derived extends Base {
action = "SAVE THE WORLD";
}
function giveMeDerived(shouldBeDerived: Derived) {
performAction(shouldBeDerived.action);
}
giveMeDerived(new Base()); // Error! The compiler has saved the world!
class Bag<T> {
items = [];
}
function putStringsInTheBag(bag: Bag<string>) {
bag.items.push("a", "b", "c", "d");
}
let bagOfNumbers = new Bag<number>();
putStringsInTheBag(bagOfNumbers); // Error! no strings going in this bag..
class Bag<T> {
items = [];
}
class BagWithMethod<V> extends Bag<V> {
putItem(item: V) {
this.items.push(item);
}
}
let bagWithMethod = new BagWithMethod<number>();
bagWithMethod.putItem(42);
let evilBag: Bag<string> = bagWithMethod; // Error! evil bag detected!
Note: this could be opt-in through a compiler flag, e.g. --nominalClassChecks
..