"What sets apart the usage of `import * as Button` from `import {Button}`

As a newcomer to Typescript, I am facing an issue while trying to import a react-bootstrap Button.

In scenario 1:

import {Button} from 'react-bootstrap/lib/Button'

In scenario 2:

import * as Button from 'react-bootstrap/lib/Button'

Both methods do not result in any errors during the import statement, but encounter errors when trying to render the Button using

<Button bsClass="glyphicon glyphicon-new-window"></Button>

In scenario 1, there is no compile time error but it shows that Button is undefined

In scenario 2, Typescript displays the following compile time error

TS2604: JSX element type 'Button' does not have any construct or call signatures.

In contrast, the same operation works in JavaScript with

import Button from 'react-bootstrap/lib/Button'
. I am puzzled as to why none of the methods are working and what distinguishes these two approaches?

Answer №1

Consider the following as the exports of a button.ts file:

export function Button () {}
export function Toggle () {}

Situation 1

When you use import { Button } from 'button', you will receive the Button function.

Situation 2

By using import * as Button from 'button', you will get an Object locally named Button with both Button and Toggle as members:

const Button = { Button:Button, Toggle:Toggle }

To learn more about module syntax, visit this link.


Since you specifically inquired about TypeScript, you may encounter issues related to why you cannot simply do import React from 'react' and must opt for the * as <x> syntax instead:

This change is influenced by TypeScript adhering to the ESModule specification. Formerly, Babel handled some behind-the-scenes actions for us developers, essentially providing interoperability between ESModules and CommonJS modules.

Imports like import React from 'react' attempt to fetch the default member in the react module. If the module is bundled with CJS, this member (usually) does not exist. Therefore, you need to employ * as React from 'react' to access the exported object containing createElement, PropTypes, and other elements.

Reference

Answer №2

The outcome varies depending on the type of object being exported from a specific module. To put it simply, let's assume module "a" exports some objects:

export {
    Button: function() { //some button construction code},
    Link: {}
}

If we have:

import {Button} from 'a'

Then Button will represent

function() { //some button construction code}

In the case of:

import * as Button from 'a'

Button will contain the entire exported object:

    {
        Button: function() {},
        Link: {}
    }

For more in-depth information, please refer to the official documentation.

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

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...

Using TypeScript 4.1, React, and Material-UI, the className attribute does not support the CSSProperties type

Just starting out with Material-UI and we're utilizing the withStyles feature to style our components. Following the guidelines laid out here, I successfully created a classes object with the appropriate types. const classes = createStyles({ main ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

React's Redux persist is causing a duplication of requests being sent

I am currently utilizing redux-persist along with Redux Toolkit. I have observed a peculiar behavior where, upon changing the slice (RTK), a request is sent to the server. When using redux-persist without a persister, only one request is made as expected. ...

Setting the default selected row to the first row in ag-Grid (Angular)

Is there a way to automatically select the first row in ag-grid when using it with Angular? If you're curious, here's some code that may help: https://stackblitz.com/edit/ag-grid-angular-hello-world-xabqct?file=src/app/app.component.ts I'm ...

I am having trouble getting the guide for setting up a NextJS app with Typescript to function properly

For some time now, I have been experimenting with integrating Typescript into my NextJS projects. Initially, I believed that getting started with Typescript would be the most challenging part, but it turns out that installing it is proving to be even more ...

Changing the button class during an event in Angular 4

In the process of creating an MCQ test, I am looking to implement a feature where selected button options are highlighted in green upon clicking. While I have successfully implemented this feature using Angular 1, I am facing challenges in converting it to ...

The variable is accessed prior to being assigned with the use of the hasOwnProperty method

Continuing my journey from JavaScript to TypeScript, I find myself faced with a code that used to function perfectly but is now causing issues. Despite searching for alternative solutions or different approaches, I am unable to resolve the problem. Snippe ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

What is the best way to emphasize when the path matches exactly with '/'?

Is there a way to highlight the path only when it exactly matches '/'? Currently, even on 'Page 2', the 'Home' link is still highlighted. Check out the plunker here .active { color: red; } <a routerLinkActive="active" r ...

Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner: private _getSPCalendarPro() { con ...

A tutorial on how to customize the hover effect for TableHead Column Identifiers in MaterialUI by adjusting

I'm struggling to customize the appearance of child th elements using the TableHead component from MaterialUI. While I've been successful in modifying various properties, I'm facing difficulty in changing the hover color. Below is the snipp ...

Tips for effectively managing TypeScript values with various types

I am currently facing an issue with the TS interface shown below: export interface Item { product: string | Product; } When I try to iterate through an array of items, I need to handle the type checking. For example: items = Items[]; items.forEach(ite ...

Leverage tsconfig.json within the subfolders located in the app directory during Angular build or ng-build process

In our Angular project, I am attempting to implement multiple tsconfig.json files to enable strictNullChecks in specific folders until all errors are resolved and we can turn it on globally. I have been able to achieve this functionality by using "referen ...

Leveraging the typeof Operator within a Class

How can we utilize typeof in order to specify the type of a class property? Take a look at both examples below, where example A works but example B does not. A) Works outside class const data: {age:number, name:string} = {age:10, name:'John'}; c ...

Converting ts files to js: A comprehensive guide

I am looking for a way to transform my TypeScript files into JavaScript files smoothly. The conversion process goes well with the command: nodemon --watch assets/ts --exec tsc assets/ts/*.ts --outDir assets/js However, I have encountered an issue where im ...

What is the best way to display just one record that has the lowest score out of all the records?

I need help with displaying only 1 record from the DL list that has the lowest score, instead of showing all records. In the example on stackblitz, you can see that for the first record, the DL scores are: 54, 20, and updated. Instead of displaying all 3 ...

A guide to implementing localStorage in TypeScript

When attempting to assign the object item to Product using this code: localStorage.setItem("Product", JSON.stringify(item)) The JSON string of item is not properly assigned to Product. Is there a solution to this issue? ...