1

Is there a way to tell the TypeScript compiler to not allow illegal access of private variables via the object map?

For example:

class Thing {
    private id: number;

    constructor() {
        this.id = 1
    }
}

var thing = new Thing()
alert(thing["id"]); // I want this to throw a compiler error
4
  • I think it should be an error already. But it isn't > so I'd report it as a bug. I am curious how you ended up with this scenario though :) Commented Jan 15, 2015 at 8:35
  • 1
    I've been researching TypeScript with regards to my use case. I want to use it to load other peoples scripts. But I want to force those scripts to obey the rules. If they can access a libraries private variable then it isn't going to work :) Are you sure it's a bug? I was reading this blog tedpatrick.com/2013/06/25/7-months-with-typescript and he mentions he uses the associative array to get around compiler problems. This is why I asked the question, because i don't want that to be allowed. Commented Jan 15, 2015 at 8:47
  • 1
    Protecting against intentionally-invasive external scripts isn't something TypeScript does. In general it's nearly impossible to do that kind of thing safely; if you do not trust an external script, do not run it in the same execution context as your own code. Commented Jan 15, 2015 at 18:09
  • It is something it can do. But i'm guessing from your response and from reading around about TypeScript, TS is meant to support normal javascript code. If this is the case then a switch will never be added to force this behaviour. But then why does the compiler have an argument to force an error when types cannot be inferred? var a; will fail compilation. I want a similar argument --strictTypes or something like that disables old javascript. I may be wishing for too much ;) Commented Jan 15, 2015 at 22:52

1 Answer 1

1

There seems to be an inconsistency, although it may turn out to be by design.

In the example below, the compiler determines the type of variable b, but ignores the fact it is private. To be consistent, it should either:

  • Not infer the type, or
  • Infer the type and check access

Obviously in your case you are after the second of these options.

class Example {
    private private: number;
    public public: number;

    constructor() {
        this.private = 1
    }
}

var example = new Example()

var a = example.private; // Error
var b = example["private"]; // number
var c = example["other"]; // any 
var d = example["public"]; // number

I have raised an issue for this on GitHub.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.