Search code examples
classtypescriptstatic-methods

How to initialize class static property once


Here is my code where I am mocking the User object by initializing array or users and then defining the operations on it.

import IUser = require("../interfaces/IUser");

export class User implements IUser {

    private static users: User[] = [];

    constructor(public name: string) {

        this.name = name;        
        User.users.push(this);
    }

    private static init()
    {
       //creating some users           
       new User(/****/);
       new User(/****/);
       ... 
    }

    public static findOne(login: any, next:Function) {
        //finding user in users array
    }

    public static doSomethingelse(login: any, next:Function) {
        //doSomethingelse with users array
    }
}

Basically before doing findOne(..) doSomethingelse() I need users to be created and I do not want to do something like:

public static findOne(login: any, next:Function) {
            User.init();
            //finding user in users array
        }

        public static doSomethingelse(login: any, next:Function) {
            User.init();
            //doSomethingelse with users array
        }

Is there better way?


Solution

  • You could do something like this:

    export class User implements IUser {
        private static users = User.initUsers();
    
        constructor(public name: string) {
    
            this.name = name;        
            User.users.push(this);
        }
    
        private static initUsers()
        {
            User.users = [];
            new User(...);
            return User.users;
        }
    }