Ionic 2.0.0 final typescript errors for union types

Attempting to upgrade from RC5 to 2.0.0 and I’m immediately getting new typescript errors both in Visual Studio Code and on compile.
The first specific case is a union type that is returned by the File Transfer Plugin

fileTransfer.upload(this.avatarSrc, url, options)
  .then((data) => {
    
    if (data.responseCode === 200) {
      let response = JSON.parse(data.response);
...

In this case ‘data’ is either a FileUploadResult or a FileTransferError, and because FileTransferError doesn’t have a responseCode property typescript doesn’t like it (even though it was fine before).

I have tried:

if (data instanceof FileTransferError) {
    // do something else
}

But it complains that FileTransferError can’t be found. If I import FileTransferError from ionic-native it tells me that FileTransferError refers to a type but is being used as a value.

Also tried

if (data.hasOwnProperty('responseCode')) {
    // do something
}

And it doesn’t like that either… so how should I be dealing with union types from ionic native?

After looking through the typescript docs for advanced types (Found here) it looks like your best bet is to define a function like this:

private isUploadResult(data: FileUploadResult | FileTransferError): data is FileUploadResult {
    return (<FileUploadResult>data).response !== undefined;
}

Then use it like so:

fileTransfer.upload(this.avatarSrc, url, options)
  .then((data) => {

    if(this.isUploadResult(data)) {
        if (data.responseCode === 200) {
          let response = JSON.parse(data.response);    
...

In my testing this makes the typescript linter/compiler happy.

2 Likes

You could try:

if (data && data.responseCode === 200)

I’m sorry, I re-read your question and this might not work the way you want.

That’s the way, thank you!