1

Consider the following little snippet:

class BlueprintNode {
    private metadata: number[] = [];
}

var node = new BlueprintNode();
node["metadata"].push("Access violation, rangers lead the way.");

Demo on TypeScript Playground

How come the TypeScript compiler allows access to a private member through the use of the square-bracket notation? It even correctly detects the type of the given property. With the dot notation, it displays a compile error correctly.

John Weisz
  • 30,137
  • 13
  • 89
  • 132
  • 1
    I guess this is because the square-bracket notation works with any Object and TypeScript wants to be as close to JavaScript as possible. I think it doesn't make sense to try to restrict you from using square brackets, even if the compiler is able to checked that `node["metadata"]` is in fact a private property because you can always bypass this check by using variables like `node[propName]`. Have a look at this answer btw: http://stackoverflow.com/a/12713869/310726 – martin Sep 06 '16 at 10:36

2 Answers2

2

When accessing object properties using indexes the compiler will treat the object like this:

interface BlueprintNode {
    metadata: number[];
    [key: string]: any;
}

If you then do:

let node: BlueprintNode;
node["metadata"].push("Access violation, rangers lead the way.");

You'll get the same error as with your code.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
0

Why TypeScript allows accessing private method using square brackets:

const privateMethodClass: PrivateMethodClass = new PrivateMethodClass();

let result: boolean;

result = privateMethodClass.getFlag();  //result = false

// Accessing private method using square brackets

privateMethodClass[ "setFlag" ]( true );

result = privateMethodClass.getFlag();  //Result = true

class PrivateMethodClass {

    private flag: boolean = false;

    private setFlag( flag: boolean ): void {
        this.flag = flag;
    }

    public getFlag(): boolean {
        return this.flag;
    }
}
Pranav Singh
  • 17,079
  • 30
  • 77
  • 104
  • If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). – Ajeet Shah May 13 '21 at 10:55