1

I have the following string enum:

export enum ReportGraphTypes {
    OverallGraph = "Long description...",
    OverallByDateGraph = "....",
    MilageGraph = "....",
    FuelPricesGraph = "....",
    FuelConsumptionGraph = "...."
}

Then I map the enum to select field and use the enum key as a value. I want to pass a default value to my select field and always can do the following:
let selected = "OverallGraph"; but that's hardcoded.
I also tried:
let selected = ReportGraphTypes[ReportGraphTypes.OverallGraph]; but I got the following error:
Element implicitly has an 'any' type because expression of type 'ReportGraphTypes.FuelPricesGraph' can't be used to index type 'typeof ReportGraphTypes'.
What is the best way to assign that key to my variable?

1 Answer 1

1

Maybe try using the keyof typeof operators to get the keys? I typically use the same approach of your second solution and I hadn't had any problems with it myself so far. Perhaps it's because that approach only works for number type values. But maybe you could use a map object instead.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried also keyof typeof but still: Conversion of type 'ReportGraphTypes' to type '"OverallGraph" | "OverallByDateGraph" | "MilageGraph" | "FuelPricesGraph" | "FuelConsumptionGraph"' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.ts(2352) I guess I have to switch to map.
Yeah, it looks like string enums have an odd behavior. There’s an open issue about this very error on github. github.com/Microsoft/TypeScript/issues/29094

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.