Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle typing a response that could be success or error?

I have code like so:

socket.emit(ClientActions.LOAD_GAME_STATE, (response: GameState | ErrorResponse) => {
       // use response
});

The trouble is that if I try to access properties I would expect on a GameState object, it predictably gives me an error because those properties don’t exist on the ErrorResponse type.

How can I express that the response could be data or an error, and type it and use it accordingly? Is there a recommended way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That is the recommended way to type it, and to narrow down the type to either success or error, you should use an if statement as a type guard:

socket.emit(ClientActions.LOAD_GAME_STATE, (response: GameState | ErrorResponse) => {
    if ('<a property only in ErrorResponse>' in response) {
       // response is of type `ErrorResponse`
    } else {
       // response is of type `GameState`
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading