-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Class private members accessible from outside with brackets notation #19335
Comments
The string index notation has been an escape hatch to allow users to get hold of the private members, e.g. to use them in unit tests, etc.. it is a slightly more type safe alternative to Our experience shows that users do not stumble into this by mistake. |
Ok, I understand. |
I do not think ppl write |
Allowing it in UTs instead of casting to any is actually a good thing, and I agree this semantic is a good thing (even if I would have defined a specific different syntax for it, like a built in mapped type for exposing private fields). I'm not going to discuss philosophical topics about human behaviors, I would just feel more safe if that syntax can be disallowed by a compiler option. Thanks. |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
IMO there are so many holes already because of JS's nature this is a piddly one. And the reason its not done is that it would require either:
tslint can detect this (not private though, but any access) and issue an error. However it too can be bypassed by using an intermediary vale. |
I'm not worried about holes... I'm perfectly fine that stuff like (o as any).privateMember exist, because the code itself makes very clear it's a workaround not acceptable in production. I understand reasons why that syntax should stay allowed, but I honestly don't understand how can someone refuse to understand that people would like to disable it with a compiler option. @czhower , I'm not afraid of (1.) because it would return a value of type any. |
As this just came up in Discord, private class fields was implemented in JavaScript and then added to TypeScript in 3.8 - https://www.typescriptlang.org/play?#example/private-class-fields |
I'm concerned about private members being "legally" accessible from outside the class, since it could lead people to believe it's an acceptable way for doing it in production code.
Currently, my team believes this is an acceptable way for unit testing code.
This approach even detects the correct private member's type, so it's not a workaround to access the raw members through upcast to any...
TypeScript Version: 2.4
Code
Expected behavior:
Compiler error: "Property '_x' is private and only accessible within the class 'Test'".
Actual behavior:
No errors.
The text was updated successfully, but these errors were encountered: