-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Enums as union types aren't compatible with strings (5.0) #53304
Comments
AFAIK string enums are intentionally stricter than numeric ones, so this is probably by design. |
It's doesn't seem to be a bug. Consider this message from the lead architect of TypeScript. |
Thanks for the information! 🙏 If that's expected, should the release note be updated to highlight the fact that this only works for numbers and not for all types? It mentions that enums started as "a set of numeric constants with the same type" and that in the example "E.Foo and E.Bar (...) were pretty much just numbers". |
I think you’re right @notaphplover, this comment was a reply of a question in the PR exactly about the behavior mentioned by this issue. So it doesn’t seem to be a bug. I’ll close this as completed. |
Here is a simple way to do that.Here the example of how to convert a Typescript enum to a union type export enum PaymentSystemEnum {
APPLE = 'APPLE',
GOOGLE = 'GOOGLE'
} And it’s pretty easy type = `${PaymentSystemEnum}`; // "APPLE" | "GOOGLE" |
Bug Report
In https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#all-enums-are-union-enums, it mentions that enums can be used as union types, allowing to do this:
TypeScript Play
The issue is that this seems to only work with
number
s, but not with other types likestring
s. If we take the exact same code but replace all numbers with strings, we have this:TypeScript Play
🔎 Search Terms
enum, union, string
🕗 Version & Regression Information
This new feature was introduced in the v5.0.0, and I tested it locally in the v5.0.2 and in the sandbox with the version
5.1.0-dev.20230316
.⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
The error
Type '"42"' is not assignable to type 'E'. (2322)
is sent by TS for the codelet fine: E = '42';
.🙂 Expected behavior
This shouldn’t behave differently from numbers, so writing
let fine: E = '42';
could be allowed by TSThe text was updated successfully, but these errors were encountered: