4

I have json file test.json

{ "foo": "bar0" }

Given those types declaration


type Bar = 'bar0' | 'bar1'

interface Foo {
    foo: Bar
}

I tried to load this json

import test from './test.json'

const foo: Foo = test

And I got this error

Type '{ "foo": string; }' is not assignable to type 'Foo'.
  Types of property 'foo' are incompatible.
    Type 'string' is not assignable to type 'Bar'.

I also tried with enum

enum Bar {
    bar0 = 'bar0',
    bar1 =  'bar1'
}

Of course it works with type Bar = string

Any idea about what can be wrong?

6
  • Possible duplicate of TypeScript type inference issue with string literal Commented Oct 30, 2019 at 13:54
  • 2
    I am trying to load JSON, it's quite different Commented Oct 30, 2019 at 14:07
  • TypeScript is inferring your JSON property foo is a string, while your type Bar is a string literal. It's the same problem but just different ways of getting it. Commented Oct 30, 2019 at 14:17
  • You need first of all do JSON.parse, and second you need to do as Foo. Commented Oct 30, 2019 at 14:21
  • @Bauke The solution suggests to cast the "center" object as 'as "center"' while I do not see how I could cast it. Are suggesting that I could use a temporary object Commented Oct 30, 2019 at 15:56

0

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.