Skip to content

Typescript type-brands using unique symbol don't work #11431

@samfrances

Description

@samfrances

Describe the bug

A common technique for achieving nominal typing in typescript is to use a unique symbol declaration as follows:

declare const PostCodeType: unique symbol;

class PostCode {
  [PostCodeType]: void;
  readonly value: string;
  private constructor(value: string) {
    // TODO: validation
    this.value = value;
  }

  static create(value: string) {
    return new PostCode(value);
  }

  toString() {
      return this.value;
  }

}

As you can see from the TS playground, PostCodeType should be removed entirely in the compiled JS.

"use strict";
class PostCode {
    constructor(value) {
        // TODO: validation
        this.value = value;
    }
    static create(value) {
        return new PostCode(value);
    }
    toString() {
        return this.value;
    }
}

And indeed, using node_modules/.bin/tsc:

var PostCode = /** @class */ (function () {
    function PostCode(value) {
        // TODO: validation
        this.value = value;
    }
    PostCode.create = function (value) {
        return new PostCode(value);
    };
    PostCode.prototype.toString = function () {
        return this.value;
    };
    return PostCode;
}());

However, when I try running this code via yarn start, I get the following error.

image

(yarn build works fine.)

Did you try recovering your dependencies?

Yes

Environment

npx: installed 67 in 3.786s

Environment Info:

  current version of create-react-app: 4.0.3
  running from /home/sam/.npm/_npx/336137/lib/node_modules/create-react-app

  System:
    OS: Linux 5.4 Ubuntu 20.04.3 LTS (Focal Fossa)
    CPU: (4) x64 Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz
  Binaries:
    Node: 14.17.5 - ~/.nvm/versions/node/v14.17.5/bin/node
    Yarn: 1.22.11 - ~/.nvm/versions/node/v14.17.5/bin/yarn
    npm: 6.14.14 - ~/.nvm/versions/node/v14.17.5/bin/npm
  Browsers:
    Chrome: 93.0.4577.63
    Firefox: 92.0
  npmPackages:
    react: ^17.0.2 => 17.0.2 
    react-dom: ^17.0.2 => 17.0.2 
    react-scripts: 4.0.3 => 4.0.3 
  npmGlobalPackages:
    create-react-app: Not Found

Steps to reproduce

Download the code from this branch on github: https://github.com/samfrances/postcode-app/tree/bug-report-1
Run

$ yarn
$ yarn start

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions