'Why doesn't TypeScript complain if I try to import a non-existent default export?

I have some code that I'm converting from not-TypeScript CommonJS files to TypeScript ES6 modules, and I ran into some issues where I needed to import using import * as x instead of import x:

The original code was something like this:

const luxon = require('luxon');

console.log(luxon.DateTime.now().toString());

And then I mistakenly changed it to:

import luxon from 'luxon';

console.log(luxon.DateTime.now().toString());

... which leads to the error:

Cannot read property 'DateTime' of undefined

The problem is that luxon has no default export, and import luxon from 'luxon' turns into code like const luxon = require('luxon').default;.

So the correct import is:

import * as luxon from 'luxon'; // or even better, import { DateTime } from 'luxon'

My question is, why doesn't TypeScript complain that I'm using a non-existent default export, and is there anything I can do to make it detect this for me?

I've found that it does complain if I try to use a non-existent default export from a TypeScript module, but not from JavaScript (even if I've installed the types for it).



Solution 1:[1]

It seems that the luxon npm package doesn't include the typings, so you need to also install @types/luxon as a dev dependency.

If you already installed the types and typescript doesn't complain about the import that it has no default export, it means you have enabled allowSyntheticDefaultImports and esModuleInterop in tsconfig which doesn't work for es modules.

This is how typescript tries to import it: enter image description here

but luxon does have __esModule set to true. enter image description here

Depending on your other dependencies, I would disable allowSyntheticDefaultImports and esModuleInterop and typescript will generate the proper error:

error TS1192: Module '".../@types/luxon/index"' has no default export.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrei Tătar