Enhance a function by sending it back to save static variables

I have a similar function like this one:

export const bar = function () {
    const myItem = new MyItem();
    return function bar(param1?: number, param2?: string): void{
        ...
    };
}();

Where myItem is a variable that I use as a temporary inside the function, and I capture it in this way to avoid allocating it every time.

I wanted to add overloads to create 2 different versions:

export function bar(): void;
export function bar(param1: number): void;

It doesn't matter if this overload makes sense, it's just for demonstration purposes.

I wanted to know if there is a way to overload bar declared in this way, or if I have to make the "static" variable myItem a module variable.
I prefer to keep it "local" to the function if possible, but haven't been able to find a way yet.

Answer №1

To implement overloads in TypeScript, you can only define them on a regular function. Separate the function declaration and return clause like this:

export const foo = function () {
    const myObject = new MyObject();

    function foo(num: number): number
    function foo(str: string): string;
    function foo(numOrString: number | string): number | string {
        return numOrString;
    };

    return foo;
}();

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

Exploring methods for testing React components with TypeScript's props

I am currently tackling a react-typescript project and I am looking to conduct testing on props passed to a react component using react-testing library. Here, we have the SharedDashboardUiLatestValueWidget.tsx component: export interface SharedDashboardU ...

Angular ensures that the fixed display element matches the size of its neighboring sibling

I have a unique challenge where I want to fix a div to the bottom of the screen, but its width should always match the content it scrolls past. Visualize the scenario in this image: https://i.sstatic.net/i7eZT.png The issue arises when setting the div&apo ...

What is the relationship between Typescript references, builds, and Docker?

I am facing a dilemma with my projectA which utilizes a common package that is also needed by my other Nodejs services. I am unsure of the best approach to package this in a Docker file. Ideally, running tsc build would compile both the project and the dep ...

Utilize NodeJS and Typescript to input data into a postgreSQL database

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

What is the best way to utilize ngStyle in combination with Interpolation?

Within my application, I am faced with a challenge involving two slide bars that generate values ranging from 1 to 100. Based on these generated values, I aim to adjust the margin of a div element in accordance with the percentage output. Despite conductin ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

Extract the array structure from the resolved promises using await with Promise.all()

When I receive the values returned by using await Promise.all() in the following manner: const [apple, banana] = await Promise.all<Object, Object>([ applePromise(), bananaPromise() ]).catch(error => next(error)); An error is triggered: T ...

Steps for Adding a JS file to Ionic 3

I'm trying to figure out how to access a variable from an external JS file that I included in the assets/data folder. Here's what I've attempted: I placed test.js in the assets/data folder. In test.js, I added a variable testvar = "hello ...

Is there a way to verify if the database has been successfully saved and the API call has been

I am currently in the process of developing a function that calls two other functions. Function 1 is responsible for saving an object to a database, while function 2 performs an API call. async createMSCalendarEntry(start: Date, end: Date, name: string ...

Tips for accessing and modifying local files in Angular 2

Is there a method in Angular 2 to access files from an absolute path? I have utilized the 'filesaver' library for file saving, storing the files locally in txt/json formats. For instance: let blob = new Blob([document.getElementById(&apos ...

Enhance Leaflet Marker functionality using Typescript

I am currently tackling a project that involves using Typescript and Leaflet. Traditionally, to extend the leaflet marker in JavaScript, it is done like this: L.Marker.Foo = L.Marker.extend({...}); But when I attempt to do this in Typescript, I encounter ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...

Tips on Configuring the Attributes of a TypeScript Object in Angular 2

A TypeScript class called Atom is defined as follows: export class Atom { public text: String; public image: boolean; public equation: boolean; } To create an object of type Atom class and set its properties, the following steps are used: atom: ...

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 ...

update the value of a specific document in Firestore by specifying its

Is there a way to update document values in a Firestore collection for multiple records without manually specifying each document ID? Currently, I have a method that works for updating individual documents using their IDs, but what if I need to update a la ...

Derive a data type from a parameter passed to a function defined within an interface

I am working with a function defined in an interface as shown below: interface UseAutocompleteReturnValue { ... getRootProps: (externalProps?: any) => React.HTMLAttributes<HTMLDivElement>; } Within my interface, I aim to create a prop named rootP ...

Parent component interacting with child component

In my application, I have a header component along with registration and login components. The selector of the header component is used in both the login and registration components. There is also a button in the header that displays as a login button if t ...

Utilizing Mongoose Typescript 2 Schema with fields referencing one another in different schemas

I'm currently facing an issue as I attempt to define 2 schemas in mongoose and typescript, where each schema has a field that references the other schema. Here's an example: const Schema1: Schema = new Schema({ fieldA: Number, fieldB: Sch ...

performing resolver when needed in angular version 5

I have been working on a project using Angular and recently updated it from version 4.2 to Angular 5. Although I haven't utilized any new features introduced in Angular 5 yet. My current task involves executing a resolver on a specific route when a c ...

Typescript raises a error notification regarding the absence of a semicolon when importing a JSON module

Attempting to import a local JSON object into my Vuex store using const tree = import('@/articles/tree.json');. The setting "resolveJsonModule": true, has been enabled in my tsconfig.json and it loads successfully, however NPM is flooding the out ...