Ways to define a static variable within a function using Typescript

There is a common approach to declaring a Static Variable or Function within a Class, demonstrated here:

class SomeClass(){
  static foo = 1;
  static fooBar(){ 
    return ++SomeClass.foo;
  }
}

However, is it possible to declare a Static Local Variable directly inside a function like this?

class SomeClass(){
  fooBar(){
    static foo = 1;
    return ++this.foo;
  }
}

Answer №1

It is not feasible. The static can be declared within the class, but not inside a function.

Answer №2

Is there a way to define a Static Local Variable directly within the function, similar to this?

Unfortunately, there is no specific syntax for this in most programming languages. However, if you require a stateful function, a common pattern can be found here: https://github.com/basarat/typescript-book/blob/master/docs/tips/statefulFunctions.md

Here is an example for your reference:

class SomeClass {
    fooBar = (new class {
        foo = 1;
        inc = () => this.foo++;
    }).inc
}

let foo = new SomeClass();
console.log(foo.fooBar()); // 1
console.log(foo.fooBar()); // 2

Answer №3

I've noticed a discrepancy in @basarat's response. Please consider adding the following:

let bar = new SomeClass();
console.log(bar.fooBar());

The outcome is 1 because fooBar isn't a method but a field that happens to be a function. Hence, each SomeClass instance has its own closure for fooBar with its unique foo.

In my opinion, for a true simulation of a static local variable similar to C++, the correct answer should be 3. This is because the one method and one foo are shared among all instances. To achieve this in Typescript, you can define fooBar after the class declaration:

SomeClass.prototype.fooBar = (function() {
    let foo = 1;
    function fooBar() {
        return foo++;
    }
    return fooBar;
})();

Furthermore, I've utilized a different approach to create the closure, avoiding the need for a new class and steering clear of arrow notation. This ensures clarity regarding the reference of this if fooBar ever requires access to instance members.

If required, you could also insert a placeholder definition of fooBar() within the class body for type checking purposes; the subsequent external definition will overwrite it seamlessly.

Answer №4

Building upon the solution provided by @realh, I managed to tackle the issue entirely within the class itself:

SomeClass {
...
    fooBar = (function () {
        let foo = 1;
        function fooBar(this: SomeClass) {
            return foo++;
        }
        return fooBar;
    })();

The utilization of the this parameter is essential for accessing the class's fields.

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

TypeScript perplexed Babel with its unfamiliar syntax and could not compile it

Encountered a problem while attempting to compile typescript. It appears that babel was unable to comprehend the "?." syntax on the line node.current?.contains(event.target) export function useOnClickOutside(node: any, handler: any) { const handlerRef = ...

Adding properties to request object on-the-fly - Google Pay [Typescript]

Here is how I am constructing the payment request object: paymentRequestObject: google.payments.api.PaymentDataRequest = { apiVersion: 2, apiVersionMinor: 0, allowedPaymentMethods: [ { type: 'CARD', parameters: { allowedAuthMethod ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges. The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are n ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

Encountering an issue during the registration of reducers with ActionReducerMap: "does not match the type 'ActionReducerMap<AppState, Action>'"

Here is a simplified version of my Angular 5 application. I have a reducer that needs to be registered in the root module. The problem arises in LINE A where I encounter the following error: ERROR in src/app/store/app.reducers.ts(7,14): error TS2322: Type ...

Struggling with an issue in React and Bootstrap4 while developing an application with create-react-app

In my experience with Windows 10, I encountered two scenarios where I faced problems. The first scenario involved creating applications using the create-react-app command and installing it with npm i -g [email protected]. Scenario 1 I stopped the React s ...

The type 'RefObject<HTMLDivElement>' cannot be matched with type 'RefObject<HTMLInputElement>' in this context

Encountered an error message: Issue with assigning types: Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement&g ...

Ways to retrieve the most recent update of a specialized typing software

When attempting to run typings install in a sample project with the below typings.js file, I received a warning. How can we determine the latest version number and what does the number after the + symbol signify? { "globalDependencies": { "core-js ...

Purge React Query Data By ID

Identify the Issue: I'm facing a challenge with invalidating my GET query to fetch a single user. I have two query keys in my request, fetch-user and id. This poses an issue when updating the user's information using a PATCH request, as the cach ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

There is a delay in updating ng-if/ng-hide in real time on the HTML page

Assistance needed for implementing a slight adjustment in AngularJS with TypeScript. The requirement is to change the text of a button for 3 seconds upon clicking, then revert back to its original text. Two HTML elements are created for this purpose, each ...

Tips for modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

How can I add a parameter to a JSON URL in Angular?

I'm looking to enhance my URL by adding a new parameter, but I'm unsure of the steps needed. ts.file route(name:string) { this.router.navigate(['/homepage', (name)]); console.log('name); } service private url1 = './assets/ ...

Tips for choosing a specific quantity and adjusting its value

Just starting out with Ionic 3 and looking for some help with the code. Can anyone assist me in understanding how to change the value of an item in a shopping cart and have the subtotal reflect that change? cart.ts private _values1 = [" 1 ", "2", " 3 "," ...

Tips on how to effectively simulate a custom asynchronous React hook that incorporates the useRef() function in jest and react-testing-library for retrieving result.current in a Typescript

I am looking for guidance on testing a custom hook that includes a reference and how to effectively mock the useRef() function. Can anyone provide insight on this? const useCustomHook = ( ref: () => React.RefObject<Iref> ): { initializedRef: ...

Is there a way to determine the specific type of a property or field during runtime in TypeScript?

Is there a way to retrieve the class or class name of a property in TypeScript, specifically from a property decorator when the property does not have a set value? Let's consider an example: class Example { abc: ABC } How can I access the class or ...