How come TypeScript does not generate an error when attempting to import a default export that does not exist?

As I work on converting my code from non-TypeScript CommonJS files to TypeScript ES6 modules, I encountered an issue with the import statements. Specifically, I needed to use import * as x instead of import x:

The original snippet looked like this:

const luxon = require('luxon');

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

However, in my attempt to upgrade, I mistakenly altered it to:

import luxon from 'luxon';

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

This change resulted in an error:

Cannot read property 'DateTime' of undefined

The root cause lies in luxon not having a default export. Thus, using import luxon from 'luxon' actually translates to something like

const luxon = require('luxon').default;
.

To rectify this, the correct way to import is:

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

My inquiry is: why doesn't TypeScript alert me about utilizing a non-existent default export, and what can I do to prompt such detection? Interestingly, TypeScript does flag an erroneous default export usage within its own modules but seems lenient when dealing with JavaScript imports (even after including type definitions).

Answer №1

It appears that the npm package luxon does not come with typings included, so it is necessary to install @types/luxon as a development dependency as well.

If you have already installed the types and TypeScript is not raising any issues regarding importing without a default export, it indicates that you have enabled allowSyntheticDefaultImports and esModuleInterop in your tsconfig file, which may not be compatible with ES modules.

This is how TypeScript is attempting to import it: https://i.sstatic.net/dXJh5.png

However, luxon has __esModule set to true. https://i.sstatic.net/3zvxd.png

Depending on your other dependencies, it may be advisable to disable allowSyntheticDefaultImports and esModuleInterop so that TypeScript will generate the appropriate error message:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring subclasses in TypeScript

When working with TypeScript and defining an interface like the one below: export interface IMyInterface { category: "Primary" | "Secondary" | "Tertiary", } Can we access the specific "sub types" of the category, such as ...

The orderBy filter seems to be malfunctioning

I'm utilizing ngx-pipes from this webpage: https://www.npmjs.com/package/ngx-pipes#orderby Specifically, I am using the orderBy pipe. However, when I implement the orderBy pipe in my HTML, the information is not being ordered correctly (from minor t ...

`Optimizing bundle size in Webpack using braintree-web integration with TypeScript`

When utilizing braintree-web 3.61.0 with Vue.js 2.6.11 and TypeScript 3.8.3, I organize the necessary components of braintree-web into a service in this manner: import { client, hostedFields, applePay } from 'braintree-web'; export default { cli ...

add the string to the chat messages array in the observable

Currently, I am in the process of developing a chat application and my goal is to showcase the user's messages in the chatroom, referred to as the feed in this project. I have already implemented a function called getMessages() that displays all exist ...

Learn the steps to refresh a component in Angular 5

src/shared.service.ts public _testData:any;   set testData(value:any) {     this._testData = value   }   get testData():any {     return this._testData;   } src/header.component.ts private postValues( ...

Using React, PIXI, and Zustand can sometimes lead to stale state issues when handling mouse events

I currently have a Pixi canvas that utilizes pointer handlers. Users are able to click on a point within a 'sequence' and move it. Recently, I came across an issue with the mouse handlers having stale state. To resolve this, I began recreating t ...

Updating pointers to elements depending on their current status

I am working with an array and looping through it to create div elements. Depending on whether the divs are 'active' (determined by state), I want to assign them the ref property. The ref is also the parameter for a hook that adds an onclick list ...

Combining the `vuex-typex` npm package's `dist/index.js` for optimal performance with Jest testing framework

I initially raised this question as an open issue on GitHub. My experience with Vue.js, Vuex, TypeScript, and vuex-typex has led me to encounter syntax errors during Jest testing. I am relatively new to working with Vue.js, TypeScript, and Jest. It is wo ...

When defining properties/data in Vue mixins, the properties/data of the mixin are not accessible

A vue mixin is being used to store information (referred as `world` in the example below) that needs to be accessed in multiple vue components without having to import it every time. Check out the code snippet: <template> <ol> <li> ...

The NX monorepo from @nrwl is unable to locate the .svgr configuration file within the lib directory

Recently, I started working with NX Monorepo that consists of 2 separate react applications. In order to share icons between these apps, I decided to create an icons library. I made changes to the project.json file of the icons library and added a svg com ...

Converting a promise of type <any> to a promise of type <entity>: A beginner's guide

As a newcomer to TypeScript and NestJS, I am wondering how to convert Promise<any[]> to Promise<MyEntity[]> in order to successfully execute the following code: const usersfromTransaction = this.repoTransaction .createQueryBuilder() ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

ReactJS Error: The property 'hubConnection' is not defined on type 'JQueryStatic'

I am currently working with the Signalr library in React, but I keep encountering the following error: Property 'hubConnection' does not exist on type 'JQueryStatic'. Is there a solution to this issue? declare var window : any; import ...

How do I create a generic function in TypeScript that adjusts its behavior based on the input argument?

Is there a way to create a generic function that can accept generic arguments like Data<string, number>? Take a look at this code snippet: interface Data<T,R> { a:T; c:R; } function foo( data: Data<string, number> ){ return t ...

angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index ...

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

substitute one item with a different item

I am facing an issue with updating the address object within an organization object. I receive values from a form that I want to use to update the address object. However, when I try to change the address object in the organization using Object.assign, i ...

Removing AWS-CDK Pipelines Stacks Across Multiple Accounts

Currently, I am utilizing pipelines in aws-cdk to streamline the process of automating builds and deployments across various accounts. However, I have encountered an issue where upon destroying the pipeline or stacks within it, the respective stacks are ...

What could be causing the transparency of my buttons when viewed on my device?

Recently, I customized the appearance of buttons in my App by adding colors. Surprisingly, everything looks perfect when I test it on a local server on my PC. However, once I deploy the App to my Android device, all the buttons become transparent. In my v ...

Enabling state persistence in NextJS version 13 across multiple pages

Just getting started with NextJS and noticed that the old method of persisting components/state using _app.js is deprecated in NextJS 13. The new routing model allows for a layout.js file to house common components. However, I'm encountering an issue ...