Aziiee Aziiee - 24 days ago 9
TypeScript Question

How to instantiate an array in TypeScript which should contain strings?

I am new to TypeScript and working on a server monitoring webApp. I have a method which should save the status of pings and endpoints into an array. Then it should determine the status of the servers depending on the entries in that array. The method should be working correctly I assume, but I think I am not initialising the array in a proper way.

setServersStatus() {
let allStatus: String[] = new Array(); // Here I get a Warning "Instantiation can be simplified"
for (let server of this.servers) {
if (server.restendpoints != null) {
for (let rest of server.restendpoints) {
switch (rest.status) {
case "OK":
allStatus.push("OK");
break;
case "WARNING":
allStatus.push("WARNING");
break;
case "ERROR":
allStatus.push("ERROR");
break;
default:
console.log('status empty');
}
}
}
if (server.ping != null) {
switch (server.ping.status) {
case "OK":
allStatus.push("OK");
break;
case "WARNING":
allStatus.push("WARNING");
break;
case "ERROR":
allStatus.push("ERROR");
break;
default:
console.log('status empty');
}
}
if (allStatus.indexOf('ERROR')) {
server.status = 'ERROR';
}
else if (allStatus.indexOf('WARNING')) {
server.status = 'WARNING';
}
else if (allStatus.indexOf('OK')) {
server.status = 'OK';
}
allStatus.length = 0;
}
}


I also tried to initialize in the following way, but it didn't work:

let allStatus = []; // Here it says "Variable allStatus implicitly has an any[] type"


So how do I initialize an array properly in TypeScript?

Answer

You can declare a typed array like this

let allStatus: string[] = [];

or like this

let allStatus: Array<string> = [];
Comments