Tips & Tricks: Structural Typing (in a Nominal Type System) with ‘auto’ Type Inference

By default, JS++ uses nominal typing over structural typing. However, structural typing can be achieved using auto.

The following is a contrived example but illustrates a consideration in your application when using auto:

class Foo
{
    bool isError() { return false; }
}

auto foo = new Foo();
if (foo.isError()) {
    exit(1);
}

Now, during refactoring:

class Foo
{
    bool isError() { return false; }
}
class Bar
{
    bool isError() { return true; }
}

auto foo = new Bar(); // type changed
if (foo.isError()) { // this effectively becomes static duck typing
    exit(1);
}

Since the variable foo above effectively becomes “duck typed” (or, more precisely, structurally typed), it becomes harder for the compiler to potentially catch your errors.

While the above example is contrived, it’s not difficult to see how this can crop up in more complex applications.

Roger PoonRoger Poon
JS++ Designer and Project Lead. Follow me on Twitter or GitHub.