How To Access Private Class Members in TypeScript

Chris Cook - Apr 12 '22 - - Dev Community

I know we shouldn't access private class members. But sometimes, there is simply no way around. For instance, during unit tests we can access private members to assert the correct values. Or while debugging we want to log a private property to the console.

In TypeScript there are two ways to do this. The first option is to cast the object to any. The problem with this option is that you loose type safety and intellisense autocompletion. The second option is the intentional escape hatch. This is a bug (or feature?) in Typescript which was left open for this very purpose. It allows access to private members via bracket notation while maintaining type safety and autocompletion.

class Test {
    public foo: string = "Foo";
    private bar: string = "Bar";
    public constructor() { }
}

const test = new Test();

// cast as any
console.log((test as any).bar)

// intentional escape hatch
console.log(test['bar'])
Enter fullscreen mode Exit fullscreen mode

Check it yourself at TypeScript Playground.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player