0

So I am trying to create a class (in TypeScript) that is accessible directly without having to create new instances of it because some classes will change the variables in that class, and other classes need to refer to the changed variables.

Here is my code:

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

login(){
    this.isAuthenticated= true;
}

logout(){
    this.isAuthenticated = false;
}

isLoggedIn(){
    return this.isAuthenticated;
}

}

export default new Auth();

if I remove new from export default new Auth(), I get an error:

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

How else can I go around this?

for example I want the following scenario

Class A:

import Auth from './auth'

Auth.login()

and another class would do that:

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

If I am using new instances, then the value of that instance will always be false.

1 Answer 1

1

Just make the methods and variables within the class public and static then you don't need to make an instance of it.

For example

export class Util
{
    public static randomFromTo(from: number, to: number): number
    {
        return Math.floor(Math.random() * (to - from + 1) + from);
    }
}

Can then just do Util.randomFromTo(from, to)

Or use the singleton design pattern

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

// Using
const x = Singleton.getInstance();
x.someMethod();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.