"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

Using Typescript and React to render `<span>Text</span>` will only display the text content and not the actual HTML element

My function is a simple one that splits a string and places it inside a styled span in the middle. Here's how it works: splitAndApplyStyledContent(content: string, textType: string, separator: string) { const splittedContent = content.split(separat ...

Typescript patterns for creating a modular library design

Transitioning a JavaScript project to TypeScript has been challenging for me, especially when it comes to establishing a solid design pattern for the library's modularity. Main Concept The core functionality of my library is minimal. For instance, i ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

Expanding the Mui Typescript breakpoints within a TypeScript environment

Encountering a typescript error when attempting to utilize custom names for breakpoint values: Type '{ mobile: number; tablet: number; desktop: number;}' is not compatible with type '{ xs: number; sm: number; md: number; lg: number; xl: numb ...

Looking to extract the expiration date from an x509 certificate?

I am currently engaged in a project that involves retrieving and displaying certificate information from an Azure integration account using Angular/Typescript. One of the requirements is to show the decoded public certificate to users to extract important ...

The constant issue persists as the test continues to fail despite the component being unmounted from the

import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { act } from 'react' import Notifications, { defaultNotificationTime, defaultOpacity, queuedNotificationTime, fa ...

Failed to hit breakpoint in TypeScript file while working with Visual Studio 2019 and Webpack

We are working on an ASP.NET MVC 5 application where we are incorporating TypeScript for client-side code and using webpack to bundle everything into a single js file. TypeScript has been installed via npm. However, we have encountered an issue where setti ...

Encountering compilation errors with TypeScript files in Angular 2 while using Visual Studio 2017

Currently, I am in the process of developing an Angular 2 application Here is a snippet of the TypeScript code that I have written: import { Component } from 'angular2/core'; @Component({ selector: 'my-app', template: ' &l ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

What is the best way to incorporate Typescript React Components across various projects?

I'm venturing into developing an npm package that involves several react components implemented with typescript. As a newcomer to react and npm, I apologize if my query seems basic. Despite researching online, there isn't much information on this ...

A guide to mocking Prisma using Jest mock functionality

Utilizing prisma for database interactions and eager to implement jest-mock to simulate the findMany call. https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false brands.test.ts import { PrismaService } from "@services/mysql.service"; i ...

Exploring the Limitations of TypeScript Type Inference Using Recursive Typing

Exploring the world of Advanced Type definitions in TypeScript has been quite the challenging journey for me, as I try to experiment with different approaches. One concept I am keen on exploring is a "wizard-step-by-step" method: function fillWizardOptio ...

TSLint Alert: Excessive white space detected before 'from' keyword (import-spacing)

I'm currently using WebStorm and working to maintain a specific code style: https://i.sstatic.net/r1n7n.png However, I encounter an issue where TSLint highlights my spacing and provides the following hint: "Too many spaces before 'from' ...

Transferring information from RSC to a nested child component using the Next.js application router

Currently, I am in the process of migrating a large Pages router next.js project to the App directory. However, I have encountered a common challenge for which I am struggling to find a suitable solution. Despite being accustomed to the convenience of Reac ...

Having trouble passing a React Router Link component into the MuiLink within the theme

The MUI documentation explains that in order to utilize MuiLink as a component while also utilizing the routing capabilities of React Router, you need to include it as a Global theme link within your theme. An example is provided: import * as React from & ...

Exploring the power of combining React, styled-components, and TypeScript: Creating a functional component that encapsulates a styled component

Struggling to create a wrapper for my styled component with proper types. Imagine having a styled component defined like this: const Button = styled.button<ButtonProps>` background-color: ${(props) => props.color}; `; Now the goal is to have a ...

What location is the optimal choice for documenting logs at a debugging level?

My team and I have been deeply contemplating the best location for writing a debug-level log during our development process. We are utilizing winston in conjunction with winston-daily-rotate-file to separate out different aspects of logging, as well as ne ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

Navigating through Expo with Router v3 tabs, incorporating stack navigation, search functionality, and showcasing prominent titles

I've been working on designing a navigation header similar to the Apple Contacts app, with a large title and search function, but only for the Home Screen. All other tabs should have their own unique settings, like different titles or hidden navigatio ...

The error code TS2554 is triggered when the function expects between 1 to 2 arguments, but receives

When attempting to include { useHash: true } in RouterModule.forRoot, I encountered the following error. How can I add additional arguments? @NgModule({ imports: [RouterModule.forRoot( appRoutes, { enableTracing: true }, // <-- for debugging ...