Shouldn't be this a compiler error...

Topics: General
Oct 24, 2013 at 8:55 AM
Hi,
two weeks ago I have done some refactoring, basically changing some setters/getters into functions. Coming from .net world, I was expecting that I will get compiler errors, but there was none. Here is an example:
class Foo {
    func(a: number): number {
        console.log(a);
        return a;
    }
}

var foo = new Foo();

var f1 = foo.func;  // this is OK
var f2 = foo.func(3); // and also this
foo.func; // BUT shouldn't be this compiler error???
foo.func; has no runtime effect and is almost always error. I think that it is processed as NOP by javascript engine. The same is true for the following statement:

var a=3;
a; // compiler error???

Maybe I’m not aware and there are situation where this can be used but in real situation this is almost every time spelling error, refactoring…
Coordinator
Oct 24, 2013 at 5:16 PM
While it's basically a NOP, it's still a valid JavaScript statement.

That said, one thing we could do, or a rule that linting tools could add, would be to warn on expressions that don't appear to have an effect. This would only be a best effort, as I believe that if you use a getter as a standalone statement, it could still have side effects .
Oct 25, 2013 at 8:51 AM
Yes, it’s completely valid statement and also getters used standalone can still have effect on program execution. But in C# even getters(get properties) can’t be used standalone, you get compiler error. It’s also very confusing because if used standalone, it can be getter or setter, OK it's getter but very confusing.

So I hope that this kind of lint tools will make the way to type script compiler and rise the confidence. I daily switch different development environment and only in ts I find myself producing intentional errors to see compiler reaction. You can generate warning for the issues that don’t prevent js generation and developers can then switch on/off particular warning. And of course by default all warnings should be switched on.

For the standalone statement for preventing warning you could also parenthesis, like this:
var a = 3;
a; // warning XXXX; you can disable it
(a); // no warning even if warning XXXX is enabled.
Oct 25, 2013 at 6:09 PM
There's a solid linting project here: https://github.com/palantir/tslint . There's no NOOP detection yet but it could be added and I'm sure would be appreciated.
Nov 4, 2013 at 2:05 PM
Grajkowski, thanks for the link, I will give it a try. But still, IMO this lint stuff should be part of typescript warning system.