Skip to content
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

--erasableSyntaxOnly #61011

Merged
merged 14 commits into from
Jan 23, 2025
Merged

Conversation

RyanCavanaugh
Copy link
Member

Implements #59601

@typescript-bot typescript-bot added Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug labels Jan 22, 2025
@typescript-bot
Copy link
Collaborator

Looks like you're introducing a change to the public API surface area. If this includes breaking changes, please document them on our wiki's API Breaking Changes page.

Also, please make sure @DanielRosenwasser and @RyanCavanaugh are aware of the changes, just as a heads up.

@jakebailey
Copy link
Member

Reading #59601 (comment), do we also need to ban import foo = x.y? Or is that erasable?

@RyanCavanaugh
Copy link
Member Author

do we also need to ban import foo = x.y? Or is that erasable?

Modulo VMS restrictions, it always transforms to const foo = x.y, but I would not categorize this as an erasure

@jakebailey
Copy link
Member

ts-blank-space and Node both say no to import Foo = Bar.Baz, so that mostly settles it.

name: "erasableSyntaxOnly",
type: "boolean",
category: Diagnostics.Interop_Constraints,
description: Diagnostics.Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JSX?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Open to suggestions 🤷

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd vote no since that would curse anyone trying to use this for "purist" purposes to not being able to use JSX at all; you're already going to get an error from Node, and in other runtimes or with a loader, it might even work just fine....

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, the fact that you already have to put JSX content in a .?sx file means you can't possibly make the mistake of "not realizing enum is special" or whatever.

I thought Daniel wanted the text to say something different, which technically JSX is a non-ES runtime construct, but the phrasing would maybe get super awkward

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh that interpretation makes a lot more sense, oops

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you're already going to get an error from Node

Well you could make the same argument about all of these features right?

the fact that you already have to put JSX content in a .?sx file

Well we permit JSX in JS files 😄

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall I think it is fine either way, just a slightly weird distinction.

Copy link
Member

@jakebailey jakebailey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation seems right to me; cross checking with other tools, I don't believe we missed anything, but it might be a good idea to add a test that shows that namespaces need to be recursively checked.

@jakebailey
Copy link
Member

Worth re-noting for people watching this that ts-blank-space and Node.js' Amaro currently do not handle uninstantiated (type-only) namespaces:

@RyanCavanaugh RyanCavanaugh merged commit 2c865e4 into microsoft:main Jan 23, 2025
31 checks passed
@RyanCavanaugh RyanCavanaugh deleted the erasableSyntaxOnly branch January 23, 2025 23:56
@scottmas
Copy link

This disables ALL enums, but aren't string only enums 1 to 1 mappable to vanilla JavaScript? At runtime, as far as I can tell, a string enum behaves identical to an object composed of string values. Is this incorrect? And if not, would it be undesirable to allow string enums with this flag turned on? IMO string enums are far more ergonomic than const objects in that they are both a type and an iterable.

Sorry if this is irrelevant and the ship has sailed. Just thought I'd ask.

@ptts
Copy link

ptts commented Jan 25, 2025

This disables ALL enums, but aren't string only enums 1 to 1 mappable to vanilla JavaScript? At runtime, as far as I can tell, a string enum behaves identical to an object composed of string values. Is this incorrect? And if not, would it be undesirable to allow string enums with this flag turned on? IMO string enums are far more ergonomic than const objects in that they are both a type and an iterable.

Enums are not "erasable" syntax - they need to be transformed to become valid Javascript.

An enum like this:

// Typescript

enum Direction { 
  Up = "UP", 
  Down = "DOWN"
}

is transformed into

// Javascript

var Direction;
(function (Direction) {
    Direction["Up"] = "UP";
    Direction["Down"] = "DOWN";
})(Direction || (Direction = {}));

The flag introduced here aims at ensuring you get a type error when you write typescript syntax that is incompatible with Node's new type stripping feature (https://nodejs.org/en/learn/typescript/run-natively#running-typescript-code-with-nodejs), which enums are.

(There is a new --experimental-transform-types flag in Node which can handle enums)

@robpalme
Copy link

As @ptts says, erasable enums do not exist today.

There is a proposal to add them to TS via new as enum syntax here.

@mohsen1
Copy link
Contributor

mohsen1 commented Jan 25, 2025

@alexbit-codemod We need a codemod for this so everyone can migrate away easily!

acutmore added a commit to bloomberg/ts-blank-space that referenced this pull request Jan 29, 2025
This PR adds support for type-only/uninstantiated namespaces. i.e.
namespaces that only use `type` and `interface`.

```ts
export class C {}

export namespace C {
  export type T = string;
}
```

**Before:** Error. only `declare namespace ...` was allowed ❌ 

**Now:** Ok. namespace declaration erased ✅ 

---

The following cases remain unchanged:

```ts
// Instantiated namespace errors
namespace A { export let x = 1 }                // error
namespace B { ; }                               // error

// Ambient namespace is erased
declare namespace C { export let x = 1 }        // ok erased
declare module    D { export let x = 1 }        // ok erased

// `module`-keyword errors
module E { export let x = 1 }                   // error
module F { export type x = number }             // error
```

## Testing

Unit tests for both supported cases and unsupported cases (errors) have
been added.

## Context

This addition was motivated by
[`--erasableSyntaxOnly`](microsoft/TypeScript#61011)
and the recognition that in today's TypeScript, the only way to augment
a class with types after the initial declaration is via namespaces.
Whilst that use case can be solved using `declare namespace` that comes
with [a
hazard](https://github.com/bloomberg/ts-blank-space/blob/main/docs/unsupported_syntax.md#the-declare--hazard).
The combination of `--erasableSyntaxOnly` checks and transforming
uninstantiated namespaces provides a safer option.

Thanks to @jakebailey for brining this to our attention
microsoft/TypeScript#61011 (comment)

---------

Signed-off-by: Ashley Claymore <aclaymore@bloomberg.net>
Co-authored-by: Rob Palmer <rob.palmer2@gmail.com>
@rauschma
Copy link

Should this option imply --verbatimModuleSyntax?

@jakebailey
Copy link
Member

We discussed this heavily and settled on "no" for now, mainly because it makes our implied options complexity even worse, but also because it means those who are using this flag for reasons that aren't specifically needing the emit then have to disable some other flag (or if we made it required, be stuck).

@demurgos
Copy link

demurgos commented Mar 6, 2025

I'm coming here from the 5.8 announcement, looking for how to migrate from enums when using erasableSyntaxOnly.

A popular solution that I see is using an as const object (e.g. as documented in the handbook).

// you can also use number literals
const MyEnum = {
  Foo: "Foo",
  Bar: "Bar",
} as const;

This is usually accompanied with export type (e.g. as in the as enum proposal): export type MyEnum = typeof MyEnum[keyof typeof NodeType];

This lets you use MyEnum as a type representing the union of the variant values (here type MyEnum = "Foo" | "Bar") and on the value side you can use MyEnum.Foo or MyEnum.Bar.
There are a few downsides though:

  • You lose nominal typing since the type MyEnum is now equivalent to the string literal union, consumer can pass "Foo" directly as a literal (instead of explicitly using MyEnum.Foo).
  • You can't refer to the variant type through MyEnum.Foo, this is mainly an issue when using the enum as the tag of a discriminated union
  • Unless you use the variant name as the variant value, debugging is less convenient because there's no reverse mapping

I don't really care about the last point, and it's easy to use the variant name anyway (it will most likely be interned by the JS engine, so perf should not be a big concern when comparing using a number VS a short string).

On the other hand, I'd like to have a way to keep nominal typing and lightweight type syntax for variants. Here is what I ended up moving to:

const Foo: unique symbol = Symbol("Foo");
const Bar: unique symbol = Symbol("Bar");

const MyEnum = {
  Foo,
  Bar,
} as const;

type MyEnum = typeof MyEnum[keyof typeof MyEnum];

declare namespace MyEnum {
  type Foo = typeof MyEnum.Foo;
  type Bar = typeof MyEnum.Bar;
}

export {MyEnum};

This uses unique symbol for nominal typing, which requires either a static readonly class property or a simple const. Using a class prevents you from using MyEnum as the union of all variant values, so constants must be used. I then combine it with a type namespace to provide type-level support for MyEnum.Foo.

Obviously, this approach is even more inconvenient at the implementation side, but I find it more convenient on the consumer side. The implementer side complexity is less relevant if using codegen. Symbol is also skipped in JSON.stringify for both keys and values, so if you rely on it then it won't work and you'd need a branded primitive type if you care about nominal typing. I use schema-guided serialization so it's not an issue for me, but it's worth mentioning.

The "record of symbols" approach addresses the complaints in this blog post about support variant annotations such as @deprecated: you can annotate in the namespace, or the symbol values.

I hope this message helps others when evaluating available solutions when migrating away from TS enums.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

10 participants