You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
enumAorB{A='a',B='b'};constarg={type: 1asconst};// { type: 1 }constarg2={type: "1"asconst};// { type: "1" }constarg3={type: AorB.Aasconst};// 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.)
@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.
constarg3={type: AorB.A}asconst// typed as { readonly type: AorB.A; }constarg3={type: AorB.Aasconst};// but error here
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).
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
andnumber
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
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: