Create a TypeScript module that exports classes from multiple files

I've been facing a challenge with splitting TypeScript modules containing classes into separate files. Despite searching for solutions, none have resolved my specific issue.

Currently, I have a module called store that contains two classes: Person and SerialisedRecord. When both classes are in one file, everything compiles and exports correctly.

Now, my goal is to have individual files for each class - Person.ts and SerialisedRecord.ts, following the same export structure as before. However, I'm unsure how to proceed with this setup.

Here's the initial configuration:

store.ts

export module store {

  export class Person {
    public fullName: string = '';

    constructor(firstName: string, lastName: string) {
      this.fullName = `${firstName} ${lastName}`;
    }
  }

  export class SerialisedRecord {   
    constructor(public serialised: string, public id: string) {}
  }

}

When compiling store.ts to store.js (ES5), the output meets expectations - a SystemJS module exporting both classes within one module.

System.register([], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var store;
    return {
        setters:[],
        execute: function() {
            (function (store) {
                var Person = (function () {
                    function Person(firstName, lastName) {
                        this.fullName = '';
                        this.fullName = firstName + " " + lastName;
                    }
                    return Person;
                }());
                store.Person = Person;
                var SerialisedRecord = (function () {
                    function SerialisedRecord(serialised, id) {
                        this.id = id;
                        this.serialised = serialised;
                    }
                    return SerialisedRecord;
                }());
                store.SerialisedRecord = SerialisedRecord;
            })(store = store || (store = {}));
            exports_1("store", store);
        }
    }
});

My attempted modification was:

export module store {
  export {Person} from "./Person";
  export {SerialisedRecord} from "./SerialisedRecord";
}

However, this resulted in an error message stating:

error TS1194: Export declarations are not permitted in a namespace.

If you could provide guidance on what I might be doing incorrectly, it would be greatly appreciated.

Below is my tsconfig.json:

{
  "compilerOptions": {
    "module": "system",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "noImplicitReturns": true,
    "removeComments": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "typings/browser",
    "typings/browser.d.ts"
  ]
}

Answer №1

To optimize the functionality, consider excluding the store module:

store.ts:

export { Person } from "./Person";
export { SerialisedRecord } from "./SerialisedRecord";

index.ts:

import { Person, SerialisedRecord } from "./store";

let p = new Person("first", "last");

Edit

If maintaining the namespace structure is necessary, you may test a solution like this:

import Person from "./Person";
import SerialisedRecord from "./SerialisedRecord";

export default {
    store: {
        Person,
        SerialisedRecord
    }
}

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

Is NGX Extended Pdf Viewer the Ultimate Solution for Acrofields?

Can a universal solution be developed for PDF Forms? The example in the documentation suggests this, but the acrofield names and their quantities are already known here public firstName = 'Jane'; public lastName = 'Doe'; public country ...

Choose between creating an observable pipe within a function or storing it in a variable

Currently, I have a functional code snippet that leverages the Angular service to create an Observable pipeline. This pipeline utilizes operators like mergeMap, filter, map, and shareReplay(1) to manage user authentication and fetch the onboarding status f ...

Continually receiving the error message: "tsc.exe" has exited with an error code of 1

After I include a tsconfig.json file in my Visual Studio 2015 web solution, I encounter the error mentioned above. Furthermore, this prevents the compiler from generating js files again even when the "compileOnSave": true option is set. When I click on t ...

How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work: const workspaceReact = reactive(null) // incorrect! Cannot pass n ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

Guide to showcasing multiple paths of Firebase data on a single Angular page

I am working with a basic database structure that includes information about groups, events, and users. Here is an example: { "groups": { "123": { "name": "developers", "users": { "1": true }, "users_count": 1 } ...

Using Typescript to Convert JSON Data into Object Instances

My challenge involves a Json object structure that looks something like this: { "key" : "false", "key2" : "1.00", "key3" : "value" } I am seeking to convert this in Typescript to achieve th ...

What is the method to confirm if a property is accessible in php?

When it comes to classes with private properties, the property_exists() function is capable of returning true (for php versions >5.3). Similarly, for functions, we have the is_callable method which not only confirms the existence of the method but also ...

Using C++ with and without the "throw()" specifier in a method or constructor signature for a custom exception handling

As a novice in C++, I must apologize for what may seem like a trivial question. I am reaching out here because my search on stackoverflow did not yield any satisfactory answers. While learning about exceptions in C++, I decided to experiment with custom e ...

Apply a CSS class once a TypeScript function evaluates to true

Is it possible to automatically apply a specific CSS class to my Div based on the return value of a function? <div class="{{doubleClick === true ? 'cell-select' : 'cell-deselect'}}"></div> The doubleClick function will ret ...

Are there alternative methods to navigate in Angular 6 that are similar to the navigation in Ionic 3?

I'm currently facing an issue with navigation in Angular 6. In Ionic, we can navigate to a different page by using navCtrl.push('ExamplePage'); However, in Angular 6, I am having trouble navigating through a button click like this: app.co ...

The Context API's `useContext` hook appears to be malfunctioning, persistently

My situation is as follows: export const LocationContext = createContext(null); export const LocationProvider = LocationContext.Provider; export const useLocationContext = () => useContext(LocationContext); Using the Provider: export const Search = () ...

In order to retrieve specific object attributes using the unique identifier

I am currently managing 2 API's referred to as teachers and sessions. The contents of the teachers JSON file are: [ { "teacherName": "Binky Alderwick", "id": "01" }, { "teacherName": "Basilio Gregg", ...

Transform the dynamic JSON format into a key-value pair structure with nested children nodes

Looking to convert a dynamic JSON structure into a tree node: { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate& ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

Crafting a model for arrays of objects - a guide to perfection

Why am I experiencing errors in the console when trying to set the API return to a variable? How can this issue be resolved? This is my TypeScript code: public myData = new myDataModel(); getData(){ this.myCoolService.getDataAPI() .subscribe(( ...

Refactor and rename with VSCode and TypeScript without having to manually open the files being affected

When working with a TypeScript application in Visual Studio Code, is there a way to rename a variable or function without the affected files automatically opening in the Editor area? I prefer my refactorings to be applied immediately and the affected file ...

Exploring the use of the React hook "useMemo" with an array as a dependency

Recently, I started using react with typeScript and came across a problem while using the useMemo hook. Below is the code snippet from my fetching service: export default class FetchingService { datas: Data[] = []; constructor() { this.f ...