Guide to implementing an "export default" with various types and values in a TypeScript module

There is a simple way to export multiple values as default:

class Car {...}
class Bus {...}

export default { Car, Bus }

You can also easily export a type as default

export default interface Airplane {...}

However, exporting multiple types as default is not allowed

interface Airplane {...}
interface Motorcycle {...}

// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Airplane, Motorcycle }

And mixing multiple types and values as default is also not supported.

class Car {...}
interface Motorcycle {...}

// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Car, Airplane }

If you need to achieve this, there may be alternative solutions to explore.

Answer №1

Explore the functionality of the export = syntax.

With the export = syntax, you can designate a single object to be exported from the module. This object could range from a class, interface, namespace, function, or enum.


VehicleModule.ts

namespace VehicleModule {
    export class Car {
        // ...
    }

    export class Bus {
        // ...
    }
}

export = VehicleModule;

TestFile1.ts

import VehicleModule from './VehicleModule';

const car = new VehicleModule.Car();
const bus = new VehicleModule.Bus();

TestFile2.ts

import { Bus, Car } from './VehicleModule';

const car = new Car();
const bus = new Bus();

For more information, visit https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require

Answer №2

When you export in this manner:

class Car {...}
interface Motorcycle {...}

// 'Airplane' is only a type reference, but it is being treated as a value in this context. ts(2693)
export default { Car, Airplane }

What you are doing is **exporting a default object with two properties*.*

Subsequently, in your code, you can import it like this:

// name it as you prefer for the default import
import transport from transport;

and utilize it as follows:

....new transport.Car()
....new transport.Plane()

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

Deploy the Angular standalone component numerous times across a single page using Bootstrap

Edit After receiving input from Andrew, I have decided to adjust my strategy: Replacing survey-angular with the survey-angular-ui package Implementing a widget approach similar to the one outlined in this example Developing a single module that encompass ...

Increase the ngClass attribute's value

Is there a way to automatically increment a numeric value in a class using the ngClass directive? For example, can we achieve something like this: <some-element [ngClass]="'class-*'">...</some-element>, where the asterisk (*) will in ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

Is there a way to establish a pre-defined key in a mat-table?

I am fetching data from an API and I need to display it in a key-value format on a mat table. The keys are predefined and not provided by the API. The data retrieved from the API is shown here: image1 I want to display it on a mat table like this: mat ta ...

Transmitting MQTT information through an application programming interface

In my project using Ionic React, I am developing an application to showcase temperature data. To achieve this, I have established an API that transmits MQTT temperature information and utilize Axios for data retrieval. Despite my efforts, I am encountering ...

Issue with TypeScript: Assigning type 'type' to 'IntrinsicAttributes & type & { children?: ReactNode; }' is not allowed. What is the solution?

I'm currently working on a small home project to enhance my skills in TypeScript. Everything was running smoothly with retrieving data from the server and displaying posts without any errors. However, when I decided to separate the code with the map i ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

Tips for implementing conditional styling (using else if) in a react component

Currently, while iterating through a list of header names, I am attempting to change the CSS style of a react component based on three different conditions. I have managed to make it work for one condition, but I am facing challenges when trying to impleme ...

The issue arises when attempting to drop elements from two lists with incorrect positions and mismatched coordinates

Angular 9 had a working version of this, which you can find here: https://stackblitz.com/edit/two-drop-list-problem-zp556d?file=package.json Now in the new Angular 14 version: https://stackblitz.com/edit/angular-ivy-1jvbnn?file=src%2Fapp%2Fapp.component ...

I implemented progress bars in Angular 2 that have changing maximum values. The service updates the maximum value for each bar dynamically. Currently, the progress bars are functioning at 100% capacity

this.games=[ {"val":50, "name":"Articlescontributed","max":35}, {"val":30 ,"name":"Articlesrated", "max":999}, {"val":20, "name":"Views", "max":35}, {"val":30, "name":"Ratings", "max":35}, {"val":20, "name":"Follower", "max":200}, { ...

Attempting to call a function with a template variable is not allowed

@Component({ selector: 'modal', ... }) export class SimpleModal { modalOpen: boolean; isModalOpen(): boolean { return this.modalOpen; } } <modal #modalRef> <div *ngIf="modalRef.isModalOpen()">...</div> </mo ...

How can you implement a null filter in the mergeMap function below?

I created a subscription service to fetch a value, which was then used to call another API. However, the initial subscription API has now changed and the value can potentially be null. How should I handle this situation? My code is generating a compile e ...

Setting a default check on a checkbox within an ngFor loop in Angular 2

I'm attempting to initialize a default value as checked for a checkbox within my ngFor loop. Here is an array of checkbox items I am working with: tags = [{ name: 'Empathetic', checked: false }, { name: 'Smart money', che ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

Having trouble looping through an array in Angular 2?

I am currently using a FirebaseObjectObservable to retrieve the value of a property from my firebase database. The property can have multiple values, so I stored them in a local array variable. However, I ran into an issue while trying to iterate through ...

"Navigate to another screen with the FlatList component upon press, displaying specific

I've created a flatlist of countries with a search filter using an API. I need help implementing a feature where clicking on a country's name in the list redirects to a screen that displays the country's name and number of cases. The screen ...

Can you explain the meaning of <T = MyType>?

While exploring a TypeScript file, I stumbled upon this interface declaration: interface SelectProps<T = SelectValue> extends AbstractSelectProps { /* ... */ } I've searched through the TypeScript handbook for <T = but couldn't find an ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...