Deba
Deba

Reputation: 989

How to dynamically form Constant string in Javascript and Typescript

I have a constant class in Typescript and it has the followings.

export class Constants {
    public static readonly SERVER_1: string = "server url 1";
    public static readonly SERVER_2: string = "server url 2";
    public static readonly SERVER_3: string = "server url 3";
    .....
    public static readonly SERVER_21: string = "server url 21";
}

In my Processor class, I need to form the object and I push to an array like this for processing.

export class Processor {

    public areReachable(): void {
        const myObject1: ServerReachObject1 = new ServerReachObject(Constants.SERVER_1);
        const myObject2: ServerReachObject2 = new ServerReachObject(Constants.SERVER_2);
        const myObject3: ServerReachObject3 = new ServerReachObject(Constants.SERVER_3);
        .....
        const myObject21: ServerReachObject21 = new ServerReachObject(Constants.SERVER_21);
        const sModelArray: DNSServerModelInfo[] = [];
        ftpModelServerArray.push(myObject1, myObject2, myObject3 ..... myObject21);
    }

}

Is there any better way to write the above. In future, the servers may be added. My senior team members are suggesting me to write in a better way. Please suggest me and help me.

I tried to write like this.

for (let i = 1; i < 22; i++) {
    const dynamicServerName = Constants + ".SERVER_"+i;
    const myObject1: ServerReachObject = new ServerReachObject(dynamicServerName);
    const sModelArray: DNSServerModelInfo[] = [];
    ftpModelServerArray.push(sModelArray);
}

But it is not working. My objective is to form the string dynamically from the Constant class instead of declaring manually one by one. Please help me.

Upvotes: 3

Views: 1603

Answers (1)

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

Please consider using a const object instead of a class with const fields. You can then iterate the server url values with Object.values().

type ServerConstants = {
    readonly [name: string]: string;
}

export const Server: ServerConstants = {
    SERVER_1: 'Server url 1',
    SERVER_2: 'Server url 2'
}

Server.SERVER_1 = 'foo'; // throws error correctly because of readonly in ServerConstants type

Object.values(Server).forEach(value => console.log(value));

Upvotes: 1

Related Questions