Hello. Help solve the error in TypeScript code. There is a function that makes a request to the server:

http.get(url) .then((API: IResponse) => { if (API.data.response) { console.log(API.data.response); } else if (API.data.error) { console.log(API.data.error); } }); 

The server always returns two kinds of objects.

In case of error:

 { data: { error: { error_code: number error_msg: string } } } 

And if successful:

 { data: { response: {} } } 

The response object can store any fields and values ​​(Depends on the request). I described the interface like this:

 interface IResponse { data: IResponseSuccess | IResponseError; } interface IResponseSuccess { response: {}; } interface IResponseError { error: { error_code: number | string; error_msg: string; } } 

Unfortunately, the TypeScript compiler produces errors:

  • Property 'response' does not exist on type 'IResponseSuccess | IResponseError'.
  • Property 'error' does not exist on type 'IResponseSuccess | IResponseError'.

    1 answer 1

    Since at the time of compilation TypeScript does not know which type of data will come, it throws the specified exception.

    To solve, you can directly specify the type of variable

     if ((<IResponseSuccess>API.data).response) { console.log((<IResponseSuccess>API.data).response); } else if ((<IResponseError>API.data).error) { console.log((<IResponseError>API.data).error); } 

    Or use an example from the textbook and tell the compiler

     function A(API: IResponse){ var data = API.data; if (isResponseSuccess(data)) { console.log(data.response); } else if (data.error) { console.log(data.error); } } function isResponseSuccess(data: IResponseSuccess | IResponseError): data is IResponseSuccess{ return (<IResponseSuccess>data).response !== undefined; } 

    Example link