microsoft / microsoft/TypeScript

`import './file.json'`: This module is declared with using 'export ='

Open
#37,623 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

In short, JSON files's implied type definition is always defined via export =, even if I'm using module: es2015, causing it to error unless I use an unnecessary flag (allowSyntheticDefaultImports)

TypeScript Version: 3.9.0-dev.20200326

Search Terms:

import require json module commonjs es2015

Code

import list from "./list.json";

for (const item of list) {
	console.log(item)
}
{
	"compilerOptions": {
		"outDir": "distribution",
		"target": "es2017",
		"module": "es2015",
		"moduleResolution": "node",
		"resolveJsonModule": true,
		"strict": true
	},
	"files": [
		"index.ts"
	]
}

Expected behavior:

list is of type string[]

Actual behavior:

index.ts:1:8 - error TS1259: Module '"./list"' can only be default-imported using the 'allowSyntheticDefaultImports' flag

1 import list from "./list.json";
         ~~~~

  list.json:1:1
    1 [
      ~
    This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.


Found 1 error.

Workaround:

  1. allowSyntheticDefaultImports: true works as expected, but that flag is unsafe and I don't want (need) to use it.
  2. declare module './list.json' {
    	const list: string[];
    	export default list;
    }
    

Playground Link: repro.zip

Related Issues: https://github.com/microsoft/TypeScript/issues/15146

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.

Research direction

Start with the repro.zip linked in the issue, especially index.ts, list.json, and the tsconfig settings for resolveJsonModule and module: es2015. Compare the behavior with the related issue #15146; done means the shown default import type-checks without allowSyntheticDefaultImports and list is inferred as string[].

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.