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?
>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`
}
});