-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Description
Search Terms
private
Suggestion
Use symbol instead of WeakMap to simulate private names (#name).
Example:
class Test {
#foo = 1;
}should become:
const _foo = Symbol('foo');
class Test {
[_foo] = 1;
}Use Cases
- It uses the same syntax as accessing other non-private field, for example:
this.#fooisthis[_foo]this.#foo = 2isthis[_foo] = 2this.#foo++isthis[_foo]++class Test { #foo = 1 }isclass Test { [_foo] = 1 }
-
Less boilerplate. Not only accessing a field is less verbose and more familiar, but it doesn't require additional helpers like
__classPrivateFieldGet -
Most importantly. You can debug the instance with private names more easily. Right now, it's a real pain.
The private names with symbols will be visible and accessible using developer console in browser, as the native private fields are.
There no real reason why they shouldn't be. So called "hard" privacy can be easily broken with monkey patching WeakMap and there no real benefit from hiding it from user.
Note that when using symbols, you will still get all that actual benefits of using private names, like uniqueness (they cannot be overwritten).
Here's a POC how you can access the private names:
http://www.typescriptlang.org/play/index.html#code/PTAEFsHsDsGsFMCeoAOBDALgYwBagOrxqwCyaKAsAFBYwDOGqATgJYBum8ZKdoAvKGjwA7gSKlyAHjTREAGlABleBkmFi3abIUzEAPgMAKAJQBuarWgNQw8d2WMB6iSgB0KJpAxfEKeK7oVcypnbndPbwxff0DHUAAzAFdoLAwWGFBYwwREAC5QXQUOABtE+HzdY1AAb2pQetBLa1iAMUgmAHkAIwAreFT+ZnZObjpXAHMVbKQzOoaWeNBDAEJW9u6+1Kraqga9mztyB1csNGLiww9hjC5yOgUchSFRB0MAbVAMHBZeAF1jWa7BoAX1A8GKgRqc32mRUbU6vX6GFcaAAJqjDF8foC9sDoaAmCpEkxoAcNEcVCczhcsfdQI9QCUyoDgcFqCBQJNGGgsFh4HQ6O0EkKrhwbgkWODUXRqEkUmkMjy+QKAAqsMXwFqS4rSyQAFT0hkgvQq2lArgt8W10vy00QkEWeuMb3+UKB9SajDWCM2cVFIzuEymxp6OPmi0M3o2SO2+L2noKvP5gqYg2qoLQvD1wRhHvojBYNyYmCFAijiNSriZ-JMOdz8SFhgTVqloAdEqldFj7tzeasjH9N24g0L8GL3iYriEAA8MCYq2cynXe-Vo5XUfArUI1ZA-EwooYlcn2goWzqFDsV7mubaqnw9EMNWEuUbesY5HGr7CMPlq-wH5eX69oOtxuFkIZFIu8BhkB9TAh+Pa9sCMH7HiiENISGDEqSR4Cu0y6gGheyYdhwRoeyYDwNOaDgCgxTwI0xSZjKNBMQKoB6vyjCAfUADEDaQIMACMBG8V0aCpgIADkaBSQR+JcsKkAmG6vYkSSnzfGM-GQJABHkT2iniUwKk8fs6mkrSrhiRJ+nUAZCY3NYAjPBxXG1tQFj5omyopoMuF0Gq1yatadCYlxChSQJUmRcZUmAk0kD0a4xSQOM4UMK4AkKE5yLGToSZ4UwyxZbpBW+e0JXGWYoAckJOgKPVBTUAFlWlYJAgAEzBK1xWuMZgxSV0cleVYSX+Kl6W5e1OVcf1EnlcefXZT5S1VRJNUcp1ChdAo22gF0QA
Examples
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.