Skip to content

Importing arrays from JSON results in incorrect type checking #34997

Closed
@dmaretskyi

Description

@dmaretskyi

TypeScript Version: 3.8.0-dev.20191105, 3.7.2

Search Terms: JSON incorrect type checking

Code

import data from "./data.json";

interface Foo {
  str: string;
}

const a: Foo[] = data.foo; // no error
const b: Foo[] = data.foo; // compilation error

interface Bar {
  bool: string;
}

const c: Bar[] = data.foo; // no error (even though the types don't match)
const d: Bar[] = data.foo; // compilation error

data.json:

{
  "foo": [
    {
      "bool": true,
      "str": "123"
    }
  ]
}

Expected behavior:

Both assignments to a and b shouldn't error. Assignments to c and d should both error.

Actual behavior:

It seems like the first assignment per type is always treated correctly by tsc while the latter ones are all compilation errors. This happens regardless whether the types actually match or not.

Removing the lines with errors results in successfull compilation even though the types don't match.

Repo with example: https://github.com/Marik-D/typescipt-issue

tsc output:

index.ts:8:7 - error TS2322: Type '{ bool: boolean; str: string; }[]' is not assignable to type 'Foo[]'.

8 const b: Foo[] = data.foo;
        ~

index.ts:15:7 - error TS2322: Type '{ bool: boolean; str: string; }[]' is not assignable to type 'Bar[]'.

15 const d: Bar[] = data.foo;
         ~

tsconfig:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "strict": true,
    "outDir": "dist"
  }
}

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions