How to export a class from a function in Typescript

Here is the objective I'm aiming to accomplish:

loadDependency(function(dep){   
    //error, can't use export within a function
    export class MyClass {
        myF(){
            dep.myStuff();
        }
    } 
});

I am restricted to creating the class within a scope that has access to dep.

The loadDependency function will be invoked only once. I prefer to continue using internal modules.

Is there a workaround to deceive the compiler into achieving this?

My ultimate goal is to enable auto-completion in other files. For example: var a:MyClass.

Answer №1

To create classes at the module/namespace level and instantiate objects of them when needed, you can follow this approach:

export class MyClass {}

loadDependency(function(dep) {
    let myInstance = new MyClass();
    // do something with myInstance, MyClass, and dep
});

This way, you will have access to MyClass from other files as well.

The reason why exporting in your example doesn't work is because export only functions within the module or namespace context. It's a static declaration that specifies the availability of the class outside the module or namespace.

For instance, this:

export class MyClass {}

translates to:

define(["require", "exports"], function (require, exports) {
    "use strict";
    var MyClass = (function () {
        function MyClass() {
        }
        return MyClass;
    }());
    exports.MyClass = MyClass;
});

Similarly, this:

module moo {
    export class MyClass {}
}

Gets converted to:

var moo;
(function (moo) {
    var MyClass = (function () {
        function MyClass() {
        }
        return MyClass;
    }());
    moo.MyClass = MyClass;
})(moo || (moo = {}));

(assuming target ES5 and default module system is CommonJS).

If you require the dep inside the class, pass it as a parameter to the constructor like this:

export class MyClass {
    private dep: any;

    constructor(dep: any) {
        this.dep = dep;
    }

    myF() {
        this.dep.myStuff();
    }
}

loadDependency(function(dep) {
    let myInstance = new MyClass(dep);
});

In conclusion, ensure the proper scope while defining classes for successful access across different modules.

Answer №2

Deceive the compiler.

var TrickyFunction = function(dependency){ 
    if(!dependency)
        return null;
    class TrickyClass {
        someFunction(){}
    }
    class AnotherTrickyClass {
        anotherFunction(){}
    }
    return true ? null : {TrickyClass:new TrickyClass(),AnotherTrickyClass:new AnotherTrickyClass()};
}   

export var TrickyClasses = TrickyFunction(null);
loadDependency(someFunction);


var test:typeof TrickyClasses.TrickyClass = null; //enables autocompletion

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

Cannot display value in NumericFormat when using MUI TextField due to prefix restrictions

When using MUI TextField with the NumericFormat and prefix prop, there seems to be an issue. If I start typing a number quickly, only one digit gets registered. On the other hand, if I type slowly all my numbers show up but the prefix disappears. All inp ...

When using Vue with Vuetify, be aware that object literals can only specify known properties. In this case, the type 'vuetify' does not exist in the ComponentOptions of Vue with DefaultData

Started a fresh Vue project with TypeScript by following this guide: https://v2.vuejs.org/v2/guide/typescript.html If you don't have it installed yet, install Vue CLI using: npm install --global @vue/cli Create a new project and choose the "Manual ...

Issue with IE11: Main.js unable to load app.module.js as ./app.module

My angular2 project is currently functioning smoothly in the latest versions of Chrome and Firefox. I am using gulp for my build automation process and systemjs for module loading. However, when I try to access the application in IE11, it fails to load a ...

Implementing circular generic in Typescript tutorial

I have a question regarding the code snippet below: interface BaseProps<TControl> { onEvent: (control: TControl) => void; } class BaseControl<TValue, BaseProps<any>> { onBlur = () => { onEvent(this); //subscriber must see ...

Is there a way to deploy a Postgres Database using Pulumi and Docker while keeping the password secure?

How can I securely provision a Postgres database using Docker with Pulumi without exposing the password? I need to ensure that the password is not visible when inspecting the container's environment variables. import * as docker from '@pulumi/do ...

What is the secret to getting this nested observable to function correctly?

Currently, I am working on an autocomplete feature that dynamically filters a list of meals based on the user's input: export class MealAutocompleteComponent { mealCtrl = new FormControl() filteredMeals: Observable<Array<Meal>> live ...

Enhance your Typescript code by incorporating typing for response objects that include both index signatures and key-value pairs

I am grappling with how to properly incorporate typescript typings for the response object received from a backend service: { de49e137f2423457985ec6794536cd3c: { productId: 'de49e137f2423457985ec6794536cd3c', title: 'ite ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

Angular 2 lacks compatibility with SVG

I have a website where I want to include SVG images inline with my HTML using Angular 2. However, when I try to load the SVG icons within a component, they do not display correctly. Instead, I see the following: https://i.sstatic.net/Ozo6E.png You can vi ...

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

Retrieving and merging data from an API using Angular 6

Is it possible to retrieve data from an API and gather each user's posts along with their comments in a single JSON object? To fetch posts, you can utilize the following API: https://jsonplaceholder.typicode.com/posts As for retrieving comments, you ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

fp-ts/typescript steer clear of chaining multiple pipes

Is there a more concise way to handle nested pipes in fp-ts when working with TypeScript? Perhaps using some form of syntactic sugar like Do notation? I'm trying to avoid this kind of nested pipe structure: pipe( userId, O.fold( () => set ...

Is there a way to package extra files along with `NodejsFunction` in Node.js?

I am looking to add another HTML file to the source code, like shown below. https://i.sstatic.net/OyxDM.png Here is my current code: const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', { runtime: lambd ...

"Learn the trick of converting a stream into an array seamlessly with RxJs.toArray function without the need to finish the

In order to allow users to filter data by passing IDs, I have created a subject that can send an array of GUIDs: selectedVacancies: Subject<string[]> = new Subject(); selectedVacancies.next(['a00652cd-c11e-465f-ac09-aa4d3ab056c9', ...

"Defining the structure of object parameters in a function using type

What is the correct way to set typing for object style parameters? The function signature I have is as follows: private buildURI({ endpoint params }): void { } Typescript is throwing an error for missing typings, so I attempted the following: private ...

Utilizing Gulp and Browserify with TypeScript to Streamline Browser Development

Here's my issue: Using gulp+browserify to compile my TypeScript to JavaScript for normal HTML pages, my class isn't available in the browser: VM633:1 Uncaught ReferenceError: Test is not defined at <anonymous>:1:13 This is my TypeScr ...

Deactivate the react/jsx-no-bind warning about not using arrow functions in JSX props

When working with TypeScript in *.tsx files, I keep encountering the following error message: warning JSX props should not use arrow functions react/jsx-no-bind What can I do to resolve this issue? I attempted to add configurations in tslint.json js ...