2

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?

1 Answer 1

2

You can declare a typed array like this

let allStatus: string[] = [];

or like this

let allStatus: Array<string> = [];
Sign up to request clarification or add additional context in comments.

1 Comment

This also works: let allStatus = <string[]>[]; I would however recommend the first declaration.

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.