Skip to content

Allow const assertion to be use on enum types  #30690

Closed
@dragomirtitian

Description

@dragomirtitian

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions