Home > Enterprise >  How to make a conditional type annotation?
How to make a conditional type annotation?

Time:03-16

How can I conditionally make type annotations on variables. I've got a function with an argument that is changing the behaviour of an api call. The behaviour is changed in such a way that the response differs. I want to type that but wasn't able to to do so after hours of research.

Thats the situation ("PseudoCode").

async search(withDetails = false) {
  const query = {
    withDetails
  }
  const data: MyApiResponse = await axios.post(uri, query)
}

That's what I want to achieve.

async search(withDetails = false) {
  const query = {
    withDetails
  }
  const data: withDetails ? ResponseWithDetails : ResponseWithoutDetails = await axios.post(uri, query)
}

CodePudding user response:

You can do it with this way

async search(withDetails = false) {
  const query = {
    withDetails
  }
  const response = await axios.post(uri, query)
  const data = withDetails ? response as ResponseWithDetails : response as ResponseWithoutDetails
}

CodePudding user response:

Since the code may see either type at runtime, you have to allow for both. Usually you'd use a union type, and then when you need to know whether there are details, you'd look at some aspect of the response that tells you whether there are details (for instance, check the presence of a property that only exists on ResponseWithDetails; I've used details in the example):

async search(withDetails = false) {
    const query = {
        withDetails
    };
    const data: ResponseWithDetails | ResponseWithoutDetails = await axios.post(uri, query);
    // ...code that uses the common parts of that type...
    // If code needs to know there are details:
    if ("details" in data) {
        // Here, TypeScript knows `data` is `ResponseWithDetails`
    } else {
        // Here, TypeScript knows `data` is `ResponseWithoutDetails`
    }
}

This avoids using any type assertions (as whatever), which is generally best when you can avoid it because it's easy to make a false type assertion and find your types don't accurately reflect the runtime values they're supposed to reflect.

  • Related