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

Is it possible to annotate exclusive union in TypeScript?

I’m trying to find a type for generic error handling that does something like this:

function request(): GenericError<{body:string}> {
  if (/* Some condition */) {
    return { error: "An error occurred" };
  }

  return { body: "Things went well" };
}

The goal is to infer that body exists if error doesn’t, i.e:

const response = request();

if (response.error) return;

/* TypeScript should infer that body can't be undefined here */

I don’t know if this is possible in TypeScript and this question might be a duplicate, but I don’t know how to word the problem exactly. I tried annotating the function with the answers in this question but none of them could guarantee body to exist if error didn’t, as far as I could see.

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


Typescript Playground

>Solution :

A union { error: string } | { body: string } + narrowing will do it :

function request(): { error: string } | { body: string } {
    if (/* Some condition */) {
        return { error: "An error occurred" };
    }

    return { body: "Things went well" };
}

const response = request();

if ('error' in response) { // narrowing
    response.error // OK
    return 
}

response.body // OK 

Playground

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