microsoft / microsoft/TypeScript

Account for discrepancy between soft privacy of `private` vs hard privacy of `#`

Open
#44,670 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Docs
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

With the upcoming TC39 class fields proposal landing in 2022, there is a soft private vs hard private discrepancy between vanilla JS' # and TypeScript's private. This discrepancy might not be obvious to all users and could cause issues.

Maybe the TS docs should highlight this discrepancy, or maybe we should have some kind of warning. Alternatively (and this would have to be raised elsewhere), maybe there should be a TypeScript ESLint warning for this.

TypeScript's private is soft private and has escape hatches like the ability to use bracket notation to access a private field.

The new # private field prefix is hard private and doesn't allow for this. In the example below, TS compiles private and # differently, and the console log at the bottom shows that accessing these values produces different results.

class Dog {
  #barkAmount = 0;
  personality = "happy";

  constructor() {}
}

class Cat {
    private meowAmount = 0;
    personality = "angry";

    constructor() {}
}

const fido = new Dog();
const garfield = new Cat();

console.log(
    fido.#barkAmount, // no good
    fido['#barkAmount'], // no good
    garfield.meowAmount, // no good
    garfield['meowAmount'] // fine
);

Compiles to:

"use strict";
class Dog {
    constructor() {
        this.#barkAmount = 0;
        this.personality = "happy";
    }
    #barkAmount;
}
class Cat {
    constructor() {
        this.meowAmount = 0;
        this.personality = "angry";
    }
}
const fido = new Dog();
const garfield = new Cat();
console.log(fido.#barkAmount, fido['#barkAmount'], garfield.meowAmount, garfield['meowAmount']);

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the TypeScript example contrasting private with # and the linked TypeScript ESLint project. First resolve whether the intended outcome is documentation, a compiler warning, or an ESLint warning; done requires an agreed scope and corresponding documentation or diagnostic behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
documentation, tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.