microsoft / microsoft/TypeScript

Assigning to a string fails if it was previously compared to an enum

Open
#35,824 0 comments 1 reaction 1 assignee View on GitHub

@elibarzilay is already working on this.

Since Jan 13, 2020.

Bug Domain: check: Control Flow Rescheduled
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: What is installed on the TypeScript playground

Assigning to a string fails if it was previously compared to an enum

If you run the code below in the TypeScript playground, line widgetName += 'AddSomething' errors out with Type 'string' cannot be assigned to type 'Widgets'.

However, if I cast the enum on the previous line to string (widgetName == <string> Widgets.ComparableHomeSales), everything compiles fine.

In addition, if I replace widgetName += 'AddSomething'; with widgetName = widgetName + 'AddSomething';, it also compiles fine.

Code

enum Widgets {
    ComparableHomeSales = 'ComparableHomeSales',
    PriceHistory = 'PriceHistory'
}

class WidgetDescription {
    private name: Widgets;

    constructor(name: Widgets) {
        this.name = name;
    }

    get Name(): Widgets {
        return this.name;
    }
}

// code implementation
let widgetDescription: WidgetDescription = new WidgetDescription(Widgets.ComparableHomeSales);
let widgetName: string = widgetDescription.Name;

if (widgetName == Widgets.ComparableHomeSales) {
    widgetName += 'AddSomething'; // <-- ERROR
}

Expected behavior:

widgetName += 'AddSomething'; should work

Actual behavior:

widgetName += 'AddSomething'; does not work

Playground Link:
Link

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.