Skip to content

Allow const assertion to be use on enum types  #30690

Closed

Description

Search Terms

A 'const' assertion can only be applied to a string, number, boolean, array, or object literal

Suggestion

Allow const assertion to be use on enum types. Currently the const assertion can be applied to string and number literals to get the compiler to keep literal types. But enums, which also can also produce literal types are not allowed in const assertions.

This seems inconsistent.

Use Cases

The use case I wanted to use it for is creating an object that could be assigned to a discriminated union (inspired by this SO question)

Examples

enum AorB { A = 'a', B = 'b' };
const arg = { type: 1 as const }; // { type: 1 }
const arg2 = { type: "1" as const }; // { type: "1" }
const arg3 = { type: AorB.A as const }; // Expected: { type: AorB.A; }, Actual: A 'const' assertion can only be applied to a string, number, boolean, array, or object literal.

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.

Activity

  1. RyanCavanaugh commented on Apr 1, 2019

    @RyanCavanaugh
    Member

    This wouldn't be a breaking change in existing TypeScript/JavaScript code

    Note that as const is recursive, so this would be a potential break

  2. dragomirtitian commented on Apr 1, 2019

    @dragomirtitian
    ContributorAuthor

    Ryan Cavanaugh (@RyanCavanaugh) I don't think it would be because literal types are already inferred for enums in objects. It's just that if the const assertion is directly on the enum we get an error.

    const arg3 = { type: AorB.A  } as const // typed as  { readonly type: AorB.A; }
    const arg3 = { type: AorB.A as const };  // but error here
  3. RyanCavanaugh commented on Apr 1, 2019

    @RyanCavanaugh
    Member

    Accepting PRs for this. It should be allowed only in the case E.P where E is a literal enum; PR should include negative tests for other cases which should be disallowed (e.g. O.P where O is not a literal enum).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions