Typescript allows for the creation of a static class that can be accessed without needing to instantiate it

My goal is to design a TypeScript class that can be accessed directly without the need to create new instances. This is necessary because some classes will modify the variables in this shared class, while others must reference those changes.

Below is the code I have created:

class Auth {
    isAuthenticated: boolean
    constructor(){
        this.isAuthenticated = false;
    }

login(){
    this.isAuthenticated= true;
}

logout(){
    this.isAuthenticated = false;
}

isLoggedIn(){
    return this.isAuthenticated;
}

}

export default new Auth();

When attempting to remove new from export default new Auth(), an error is triggered:

The value of type 'typeof Auth' is not callable. Did you mean to include 'new'?ts(2348)

What other approach could I take?

For instance, consider the following scenario:

Class A:

import Auth from './auth'

Auth.login()

Another class might do this:

import Auth from './auth'
if(Auth.isLoggedIn){
//do this...
}else
{console.log("not logged in");

If I use new instances, the value will always be false for each instance.

Answer №1

To avoid the need for creating an instance, you can simply make the methods and variables within the class public and static.

Here is an example:

export class Helpers
{
    public static generateRandomNumber(min: number, max: number): number
    {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }
}

This allows you to call the method directly like this: Helpers.generateRandomNumber(min, max)

Another approach is to implement the singleton design pattern:

class Singleton {
    public someMethod() { ... }
}

// Example of how to use it
const instance = Singleton.getInstance();
instance.someMethod();

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

The result should display the top 5 application names based on the count property found within the ImageDetails object

data = { "ImageDetails": [ { "application": "unknownApp, "count": 107757, }, { "application": "app6", "count": 1900, }, { & ...

What is the best way to iterate through this collection of objects?

When I print out the Array in my console, it shows like this: https://i.sstatic.net/7ZVr3.png for (let index = 0; index < employeeList.length; index++) This for loop is not functioning properly because the length is 0. I attempted different approaches ...

What steps should I take to establish a one-to-one relationship with legacy tables?

As I work on developing a web application (angular, nestjs, typeorm), I am faced with the challenge of linking two legacy user tables together within our existing system. Despite my efforts, I continue to encounter an error message related to column refere ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

Encountering TypeScript Observable Error When Sending Multiple API Requests (Angular, TypeScript, RxJS)

Encountering an Issue: ERROR in src/app/fetch-trefle.service.ts:86:31 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. 86 mergeMap((item: any): Observable<any> => { Here& ...

Unable to locate the specified nested module during the import process

Imagine a scenario where we have two packages, namely package1 and package2. When package2 attempts to import the module from package1, an error is thrown stating that the module is not found. The import statement in question looks like this: import { ... ...

Trouble integrating PDF from REST API with Angular 2 application

What specific modifications are necessary in order for an Angular 2 / 4 application to successfully load a PDF file from a RESTful http call into the web browser? It's important to note that the app being referred to extends http to include a JWT in ...

Can a circular dependency be tolerated when a type declaration file brings in an enum from the implementation?

Let's say you have an implementation file called module.ts and a type declaration file named module.d.ts. // module.ts import type ConfigI from 'module.d.ts'; export enum ConfigType { Simple, Complex } function performTask(config: Conf ...

Generating Angular component based on selector

I developed an app that showcases various visualizations of RxJS operators such as rx-map, rx-filter, rx-reduce, and more. The visualizations function correctly on their own. Now, I am looking to enable users to select which visualization they want to view ...

Struggling with continuously re-rendering a color background when using useMemo in React?

After every re-render, a new color is generated. Is there a way to store the initial color and reuse it in subsequent renders? const initialColor = generateNewColor(); // some random color const backgroundColor = React.useMemo(() => { return ...

Utilize a vacant implementation of an interface

I have a simple interface called EmployerContact. I'm wondering how I can create an empty object, mockEmployerContact, of type EmployerContact and then assign values to its properties later on. Do I need to start with default values for this object? e ...

The function mustAsync onSuccess is not present in this type (typescript)

I currently have 2 mutations that are functioning well. However, I encountered an issue when attempting to implement onSuccess and invalidateQueries. The error message displayed is as follows: Property 'mutateAsync' does not exist on type '{ ...

What is the best approach to incorporate a stopwatch?

I'm exploring ways to track the time it takes for a user to click a button. While I have a working solution, I'm curious if there's a more efficient method available. Below is my current implementation: export class MainComponent implements ...

My experience with DebugElement in Angular testing has been frustrating due to unexpected behavior

I have been experimenting with integrating test codes into my Angular project. Within the PostFormComponent, there are input bindings and an output event emitter. @Component({ selector: 'app-post-form', templateUrl: './post-form.compon ...

Guide on creating dynamic route paths for includes within a Pug template

Need help creating a dynamic include For example: h1 include path/#{object} or include path/+{object}+{a:true,b:11} Something similar to the above. If anyone knows how to achieve this using Mixins in pug, please provide an example for include. ...

Issue with Firebase Functions trigger not activating

Just delving into the world of Firebase Functions for the first time using Typescript. I've written two functions: export const helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase!"); const testRe ...

Issue in Angular form: Element removal from the DOM does not remove it at the specified index, instead removes the last item

I'm encountering an issue where the wrong element is being removed from the DOM. In my onDelete() method, I am deleting a specific FormControl at a certain index, but in the actual DOM, it's removing the last item instead of the intended one. Fo ...

Updating the value of a key in an object is not functioning as expected

There is a single object defined as requestObject: any = { "type": 'type1', "start": 0, "size": 10, "keywords": ['abcd','efgh'], filters: [], } Next, attempting to change the value for keyword, I updat ...

Issue 1068: Attribute not found within angular 2 (Ahead of Time Compilation)

I am currently learning Angular 2 and trying to create a "User Register" form. However, I encountered an error stating "Property does not exist on type" during Phone number validation. I am using both JIT and AOT compilers. With the JIT compiler, my user ...

Encountering a 504 Gateway Timeout error while attempting to send a POST request to an API route in a NEXT.JS application that

I encountered a 504 error gateway timeout when attempting to post a request to api/webhooks, and in the Vercel log, I received a Task timed out after 10.02 seconds message. This code represents a webhook connection between my clerk and MongoDB. [POST] [m ...