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.