Skip to content

Proposal: error on invalid assignments between classes that share a nominal heritage #7817

Closed
@malibuzios

Description

@malibuzios

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:

  1. B is a strict nominal ancestor of A.
  2. A is a nominal ancestor of B 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..

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions