microsoft / microsoft/TypeScript

ES6 module declarations should be marked to exclude them from `allowSyntheticDefaultImports`

Open
#27,329 6 comments 8 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

This is the restated #27293. CC @ryanelian

TypeScript Version: master (471bc64)

Search Terms: esModuleInterop allowSyntheticDefaultImports error undefined default import export

Code: In the b subdirectory, compile with tsc -b . and run with node index.js.

// tsconfig.common.json
{
    "compilerOptions": {
        "composite": true,
        "declaration": true,
        "target": "es6",
        "module": "commonjs",
        "esModuleInterop": true
    }
}

// a/tsconfig.json
{
    "extends": "../tsconfig.common.json",
    "files": [
        "index.ts"
    ]
}

// a/index.ts
export const foo = 42;

// b/tsconfig.json
{
    "extends": "../tsconfig.common.json",
    "references": [
        { "path": "../a" }
    ],
    "files": [
        "index.ts"
    ]
}

// b/index.ts
// Actual: compile OK.  Expected: compile error.
import A from "../a";
// Actual: runtime error.
console.log(A.foo);

Expected behavior: The generated a/index.d.ts uses some new syntax to mark the module as an ES6 module, so allowSyntheticDefaultImports does not apply to it and the default import in b/index.ts is a compile error.

Actual behavior: allowSyntheticDefaultImports applies to module a, so at compile time, the default import is accepted and resolves to the entire module, but at runtime, A.foo raises an error:

REDACTED/b/index.js:7
console.log(a_1.default.foo);
                        ^

TypeError: Cannot read property 'foo' of undefined

Playground Link: N/A, multiple files

Related Issues: #27293

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

Reproduce the case in the b subdirectory with tsc -b . and node index.js, then inspect the generated a/index.d.ts and the import in b/index.ts. Done means the declaration marks the ES6 module so the default import is rejected during compilation instead of causing the shown runtime error.

Written by the indexing model from the issue text.

Assessment

Tech stack
node.js, typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.