0

I was studying TypeScript myself at TypeScript's Playground page.
I'm not sure if TypeScript transpiles the code well.
I created a class and this class has a name as a private member.
So I did some test if I can access to private member of class in transpiled code.
But, I succeed to access to private member.
I was just studying TypeScript. So I think I chose wrong options maybe.

Selected Options

(Added) TypeScript Version: 3.5.1
Target : ES5
JSX : None
checked options are:

  • noImplicitAny
  • stricNullChecks
  • strictFunctionTypes
  • stricPropertyInitialization
  • noImplicitThis
  • noImplicitReturns
  • alwaysStrict

My TypeScript code

class Person {
    private _name: string;
    _age: number;

    constructor(name: string, age: number) {
        this._name = name;
        this._age = age;
    }

    setName(name: string) {
        this._name = name;
    }

    getName(): string {
        return this._name;
    }

    setAge(age: number) {
        this._age = age;
    }

    getAge(): number {
        return this._age;
    }
}

const person = new Person('James', 23);
console.log(person.getName()); // James
console.log(person._name);  // error: Property '_name' is private and only accessible within class 'Person'.
console.log(person._age); // 23

Transpiled code to ES 5

"use strict";
var Person = /** @class */ (function () {
    function Person(name, age) {
        this._name = name;
        this._age = age;
    }
    Person.prototype.setName = function (name) {
        this._name = name;
    };
    Person.prototype.getName = function () {
        return this._name;
    };
    Person.prototype.setAge = function (age) {
        this._age = age;
    };
    Person.prototype.getAge = function () {
        return this._age;
    };
    return Person;
}());
var person = new Person('James', 23);
console.log(person.getName());  // James
console.log(person._name); // James
console.log(person._age); // 23



Any suggestions?

Chris
  • 392
  • 4
  • 16

1 Answers1

3

For the moment JavaScript doesn't have truly private members; the notion of private in TypeScript is merely there to help you preventing coding mistakes. There is a possibility that in the future, ECMAScript might introduce real private members, but until then, you can still access "private members" after transpiling.

Mu-Tsun Tsai
  • 2,348
  • 1
  • 12
  • 25