2

I have a json file which looks like these:

{ 
     "ui": "Header"
}

while "ui" is an enum. I load this part with JSON.Parse in my typescript webpack envoriment with node.js and ts-loader, so my error is:

"Type 'string' is not assignable to type 'UiDescriptionTypeEnum'."

and my interface I am trying to cast into is:

interface UI
{
     ui: UiDescriptionTypeEnum
}

while having the enum like this:

enum UiDescriptionTypeEnum
{
     Header = "Header"
}

Here is a working typescript play with the error:

https://www.typescriptlang.org/play?#code/KYOwrgtgBAsgngUXBAsAKAN7qjqAJYAQwBNgAnKAXigCICTyb0BfddASxABdyAzQgMbBYcAJLc+g4eixpcUHgGcuALhFJILNmgBuhCgCtFAexBUoGBcGVqA5PVJlbUVmnQAbYFyiE18cTxk-ELmRqYA3EA

11
  • Does this answer your question? How do I convert a string to enum in TypeScript? Commented Dec 30, 2020 at 9:01
  • Thank you, it did not. I read into it, but my main problem seems the json converter here, not typescript itself Commented Dec 30, 2020 at 9:04
  • is it a case issue like Caroline pointed out? Commented Dec 30, 2020 at 9:06
  • AI allready answered that: no it isnt. Commented Dec 30, 2020 at 9:08
  • missed that, sorry. check out this one stackoverflow.com/questions/35760096/… Enum in Json in Typescript with Interface? Commented Dec 30, 2020 at 9:09

1 Answer 1

2

Values in the enum are case sensitive

try to redefine the enum as below

enum UiDescriptionTypeEnum
{
     header = "header"
}

Updated the example from the link

enum MyEnum
{
    Header = "Header"
}

interface MyInterface 
{
    test: MyEnum
}

var json = { test: 'Header' }
var jsonObj = {test: MyEnum.Header} // option 1:  to define the type from Enum

let a : MyInterface =  json as MyInterface; // option 2: cast js object to your interface ( a more likely scenario)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, did not solve my problem, I just had a typo in my question, the "Header" was upper case in my json allready, so they matched

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.