What could be the reason behind TypeScript automatically appending .default to a global import declaration?

Having a global definition within an external library file named thing.d.ts:

declare var thing: ThingStatic;
export default thing;

Importing the npm module in TypeScript:

import thing from 'thing';
...
thing.functionOnThing();

After transpiling the TypeScript (with ES6 target), it results in:

const thing_1 = require("thing");
...
thing_1.default.functionOnThing();

Leading to the error message:

Cannot read property 'functionOnThing' of undefined

The confusion lies in why TypeScript is inserting .default between thing_1 and functionOnThing().

It's important to note that there is no default property defined on ThingStatic, nor on the underlying JS object specified in the .d.ts file.

Understanding why TypeScript includes this property and how to prevent it is crucial. Can anyone provide insight on fixing this issue?

Answer №1

import item from 'item';

This snippet indicates "import the default export from the module 'item' and assign it to the variable name item".

TypeScript complies with your instruction and references the default property of the module object.

You likely intended to express:

import * as item from 'item';

Answer №2

It seems like there is a bug related to global TypeScript definitions and the use of "module": "commonjs" in the tsconfig.json.

You have two options: either stick with global TypeScript definitions and combine all your output into a single file, or switch to using modules and importing them directly.

The issue here stems from the fact that require returns the module context, and the name of the default doesn't matter - it always defaults to default...

declare var thing: ThingStatic;
export thing; // Explicit export for thing
export default thing; // Default export for thing

Now when you use require, it will return this context. With commonjs modules:

import module from 'thing';
var thing = module.default; // Retrieves the default export
var alsoThing = module.thing; // Retrieves the named export

However, I've personally experienced inconsistencies with this method, so I switched to using ES6 modules instead:

import thing from './thing'; // Imports the default export
import { thing } from './thing'; // Imports the named export
const thing = (await import('path/to/thing.js')).default; // Dynamically imports 

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

The declared type 'never[]' cannot be assigned to type 'never'. This issue is identified as TS2322 when attempting to pass the value of ContextProvider using the createContext Hook

I'm encountering an issue trying to assign the state and setState to the value parameter of ContextProvider Here's the code snippet:- import React, { useState, createContext } from 'react'; import { makeStyles } from '@material-ui ...

Despite awaiting them, promises are not resolving synchronously

I have a function that retrieves location information and returns a promise. I use mobx to manage the store, updating the this.locationStoreProp and this.hotel.subtext properties. public fetchPropertyLocation(some_input_params): Promise<any> { ...

The specified object '[object Object]' is not compatible with NgFor, which only supports binding to iterable data types like Arrays

I have some code that is attempting to access objects within objects in a template. <table class="table table-striped"> <tr *ngFor="let response of response"> <td><b>ID</b><br>{{ response.us ...

Unlocking the capabilities of Chrome extensions using Angular 2 and TypeScript

Currently attempting to develop a chrome extension using angular2 and typescript, I have hit a roadblock in trying to access the chrome API (in this case, chrome.bookmarks). I have successfully gained access to the chrome object by following guidance from ...

Processing HTTP requests routed from Firebase Hosting to Cloud Functions

I'm currently working on integrating data patching with my Firestore database using http. My goal is to achieve this without relying on an external server, by utilizing Firebase Hosting and Functions. Firstly, I set up my Firebase project and importe ...

Why isn't the background-image displaying with the use of the url() function?

I've been attempting to set an image as the background using background-img:url(imageLing), but it's not working properly. When I inspect the element, it shows me background-image: url(assets/backgrounds/5.jpg);. What could be causing this issue? ...

What is the best way to combine index signatures with established properties?

Imagine a scenario where an interface has certain defined properties with specific types, but can also include additional properties with unknown keys and various other types. Here is an example: interface Bar { size: number; [key: string]: boolean | s ...

Exploring Manipulation of M:N Associations in Sequelize

I have set up a sequelize schema using postgre DB export const Commune = sq.define("commune",{ codeCommune: { type: DataTypes.STRING(5), allowNull: false, primaryKey: true }, libelleCommune: { type: ...

Guidelines for creating a masterpage and details page layout in Angular 6

In my app.component.html file, I have the following code: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> </div> <div> <p-menu [model]="items"></p-menu> </div> Below is the code ...

Steps for sending an image to Cloudinary using the fetch API

Struggling to figure out how to successfully upload a file to Cloudinary using fetch on my front-end. After consulting the documentation and various StackOverflow threads, I'm still facing a frustrating 400 error: export async function uploadImageToCl ...

React Component - Element with an undefined value

When I tried implementing an Ionic Modal as a React Component, I encountered the following error message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type & ...

Swapping the content of the API response with Angular 11 in the HTML

When the output of row.remarks is 1, I want to display it as "passed" and when it's 0, I want it to be displayed as "fail" in the HTML while using mat-table. HTML <ng-container matColumnDef="remarks"> <th class="font& ...

Error message in CodeSandBox with Angular: TypeError - The function html2canvas_1.default is not defined or recognized

Attempting to convert a basic html table into a PDF format within my project has resulted in unexpected errors when using CodeSandbox: ERROR TypeError: html2canvas_1.default is not a function at AppComponent.downloadPDF (https://3d3bh.csb.app/src/app/a ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

Can I modify the cookie domain for NestJS SessionModule on a per-request basis?

I am currently using NestJS with SessionModule to handle user cookies successfully. However, I have a requirement to override the domain name for certain requests. I am uncertain about how to achieve this within NestJS, as the domain setting appears to b ...

Facing numerous "error TS1005" messages when performing a gulp build due to node_modules/@types/ [prop types] and [react] index.d.ts with SPFx Webpart

I am currently in the process of developing a custom spfx webpart that includes a feature to display link previews. In order to achieve this functionality, I integrated this specific library. However, I encountered some challenges during the implementation ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

'The object of type '{}' does not support indexing with a 'string'

I am currently working on a React component that dynamically generates an HTML Table based on an array of objects. The columns to be displayed are specified through the property called tableColumns. While iterating through the items and trying to display ...

The SortKey<> function is ineffective, even though the individual types it uses work perfectly fine

After my initial inquiry about TypeScript, the focus shifted to this current topic. In my previous question, I was attempting to develop a generic sort() method that could function with an array of sort keys defined by the SortKey type featured there (and ...