GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ES private field check by acutmore · Pull Request #44648 · microsoft/TypeScript

Conversation

@acutmore

@acutmore Ashley Claymore (acutmore) commented Jun 18, 2021 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Ergonomic brand checks for Private Fields

This PR implements the TC39 Stage-4 Ergonomic brand checks for Private Fields proposal

Fixes #42574

Remaining Work

  • confirm (and release) changes to tslib Add new private class element helper: __classPrivateFieldIn tslib#157

Type Checking

Checking the presence of a private field provides a strong type narrowing hint.

class C {
  #field = 1;

  static getFieldOrUndefined(value: object) {
      if (#field in value) {
          // 'value' is narrowed from 'object' to 'C'
          return value.#field;
      }
      return undefined;
  }
}

Unsoundness

Whilst the runtime check is accurate, this static check is not fool-proof. The super constructor return pattern can add a private field to an object that is not an instance of the class (different prototype). This PR opts to narrow the type without checking for this case under the assumption that this pattern is uncommon and discoverable by looking at the constructor of the super class.

Example
class Base {
    constructor(o: object) {
        return o;
    }
}

class Sub extends Base {
    #field = 1;

    constructor(o: object) {
        super(o);
    }

    method() {}

    static run(o: object) {
        if (#field in o) {
            // 'o' is now of type 'Sub' but...
            o.method(); // Throws 'o.method is not a function'
        }
    }
}

const o = {};
new Sub(o);
Sub.run(o);

Downlevel

Builds on top of the existing downlevel support for ES private class elements. If the private field is an instance field then the coresponding WeakMap is consulted. Private methods and accessors consult the WeakSet. Private static fields/methods/accessors do a direct equality check with the class constructor.

Example transform

TypeScript

class Foo {
    #field = 1;
    #method() {}
    static #staticField = 2;
    static #staticMethod() {}

    check(v: any) {
        #field in v;
        #method in v;
        #staticField in v;
        #staticMethod in v;
    }
}

function syntaxError(v: Foo) {
    return #field in v;
}

JavaScript - ES2020 emit

var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(receiver, state) {
    if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
    return typeof state === "function" ? receiver === state : state.has(receiver);
};
var _Foo_instances, _a, _Foo_field, _Foo_method, _Foo_staticField, _Foo_staticMethod, _Bar_field;
class Foo {
    constructor() {
        _Foo_instances.add(this);
        _Foo_field.set(this, 1);
    }
    check(v) {
        __classPrivateFieldIn(v, _Foo_field);
        __classPrivateFieldIn(v, _Foo_instances);
        __classPrivateFieldIn(v, _a);
        __classPrivateFieldIn(v, _a);
    }
}
_a = Foo, _Foo_field = new WeakMap(), _Foo_instances = new WeakSet(), _Foo_method = function _Foo_method() { }, _Foo_staticMethod = function _Foo_staticMethod() { };
_Foo_staticField = { value: 2 };

function syntaxError(v) {
    return  in v;
}

References

  • Spec
    • TC39 Proposal: private-fields-in-in
  • TypeScript
    • Private class elements PR in TypeScript
  • Engines
    • V8 9.1 blog
    • Chrome shipped in v91
    • FireFox shipped in v90
    • Safari merged
  • Babel
    • Package

Credits

This PR includes contributions from the following Bloomberg engineers:

  • Titian Cernicova-Dragomir Titian Cernicova-Dragomir (@dragomirtitian) : support, advice, ideas, PR review
  • Kubilay Kahveci Kubilay Kahveci (@mkubilayk) : PR review
  • Rob Palmer Rob Palmer (@robpalme) : support, advice

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

robpalme, rricard, jbhoosreddy, dnalborczyk, FilipeBeck, and jmopel reacted with thumbs up emoji mkubilayk, rricard, jbhoosreddy, dnalborczyk, and jmopel reacted with hooray emoji
All reactions
  • 👍 6 reactions
  • 🎉 5 reactions
Loading

Uh oh!

There was an error while loading. Please reload this page.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Reviewers

@sandersn Nathan Shively-Sanders (sandersn) sandersn approved these changes
@elibarzilay Eli Barzilay (elibarzilay) Awaiting requested review from elibarzilay
@rbuckton Ron Buckton (rbuckton) Awaiting requested review from rbuckton
+3 more reviewers
@mkubilayk Kubilay Kahveci (mkubilayk) mkubilayk left review comments
@Jack-Works Jack Works (Jack-Works) Jack-Works left review comments
@ShuiRuTian Song Gao (ShuiRuTian) ShuiRuTian left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

@sandersn Nathan Shively-Sanders (sandersn)

Labels

For Backlog Bug PRs that fix a backlog bug

Projects

PR Backlog
Archived in project

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Proposal private-fields-in-in is stage-3

Uh oh!

There was an error while loading. Please reload this page.

8 participants

@acutmore @typescript-bot @orta @sandersn @mkubilayk @rbuckton @Jack-Works @ShuiRuTian
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.