John White John White - 3 months ago 14
TypeScript Question

Why are private members accessible through the square bracket notation?

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.

Answer

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.