microsoft / microsoft/TypeScript

TypeScript generated invalid types if `esModuleInterop` is enabled

Open
#52,779 3 comments 0 reactions 1 assignee View on GitHub

@andrewbranch is already working on this.

Since Feb 17, 2023.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

When a package is typed using module.exports =, the correct way to type it is export =. The correct way to import this, in either .ts or .d.ts files, is import identifier = require('module'). For example import React = require('react').

If a user enables esModuleInterop, they are allowed to use import React from 'react'. When compiling to CJS, this will output JavaScript that used either module.exports.default or module.exports.

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importDefault(require("react"));

IMO This isn’t great, but it works.

What is bad, is that it generates a default import in the type definitions.

import React from 'react';

Whereas it should be typed as this:

import React = require('react');

If this is library code, that means the user of the library now is also enforced to use esModuleInterop, whether they like it or not.

🔎 Search Terms

esModuleInterop

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs

⏯ Playground Link

Playground link with relevant code (Look at the .d.ts output)

💻 Code

The following code requires esModuleInterop to be enabled.

import React from 'react'

export const element = React.createElement('div')
🙁 Actual behavior

This is the generated type definition:

import React from 'react';
export declare const element: React.DetailedReactHTMLElement<React.HTMLAttributes<HTMLElement>, HTMLElement>;
🙂 Expected behavior

This is the correct type definition:

import React = require('react');
export declare const element: React.DetailedReactHTMLElement<React.HTMLAttributes<HTMLElement>, HTMLElement>;

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.