Currently, I am developing a Discord-bot using TypeScript which includes a command to retrieve information from an airport. To do this, users only need to provide the 4-character ICAO code that identifies the specific airport. However, due to potential user errors in inputting the ICAO code, I have implemented a method that retrieves the airport object from a JSON file. Here is a simplified representation of how the method looks:
public getAirport(icao: string): Airport | undefined {
return arrayOfAllAirports.find(ap => ap.icao === icao);
}
In my command file/class, I utilize this method to fetch the airport based on the provided ICAO code. Subsequently, I check if the returned value is undefined and handle it accordingly by displaying an error message. This portion of the code appears as follows:
let airportMgr = new AirportManager();
let airport = airportMgr.getAirport(icao);
if (airport === undefined) {
return *invalid ICAO error*;
}
*additional logic*
let exampleString = `ICAO: ${airport.icao} | Name: ${airport.name}`;
^error shown here ^error shown here
On rare occasions, I encounter an error in two distinct files/classes where I use this particular method together with the defined checks. The error suggests that the 'airport' object may be undefined. Strangely, when accessing some other property of 'airport' a few lines below, no error is indicated.
While I could resolve this issue temporarily by utilizing as Airport
when retrieving or reassigning the airport, I aim to identify a more robust solution rather than circumventing TypeScript rules. Can anyone provide insights on how to effectively address this perplexing problem?
edit:
A reference picture showing the area where the code worked correctly can be viewed here: https://i.stack.imgur.com/tTZyJ.png