Skip to content

Enums as union types aren't compatible with strings (5.0) #53304

Closed
@Ayc0

Description

@Ayc0

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

image

The issue is that this seems to only work with numbers, but not with other types like strings. If we take the exact same code but replace all numbers with strings, we have this:

Type '"42"' is not assignable to type 'E'. (2322)

TypeScript Play

image

🔎 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

enum E {
    A = '42',
}

export let fine: E = '42'; // fails but should work
//         ^
export let oops: E = '43'; // fails as expected

// ====

enum F {
    Foo = '10',
    Bar = '20',
}

function takeValue(e: F) {}
takeValue(F.Foo); // works
takeValue('10'); // fails but should work
//        ^
takeValue('123'); // fails as expected

🙁 Actual behavior

The error Type '"42"' is not assignable to type 'E'. (2322) is sent by TS for the code let fine: E = '42';.

🙂 Expected behavior

This shouldn’t behave differently from numbers, so writing let fine: E = '42'; could be allowed by TS

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions