'Typescript checking for truthy value [closed]

I am fetching data in typescript and have the following types:

type GoodResponse = {
  status: 1;
  data: string;
}

type BadResponse = {
  status: 0;
  error: string;
}

type Response = GoodResponse | BadResponse

Now after fetching data, I try to check response like this:

const response = await fetchApi() // returns type Response
if (!response.status) return

const data = response.data
// Property 'data' does not exist on type 'Good Response | Bad Response.....

However if check for response.status === 0 it works properly.



Solution 1:[1]

TypeScript should be able to know the type from your example alone what verssion of TS are you using?
Either way I think it would be best to use User type predicates in case the way to distinguish between responses ever changes:

const isBadResponse = (response: Response): response is BadResponse => !response.status;

const response = await fetchApi() // returns type Response
if (isBadResponse(response)) return;

// Now TS knows response is of type GoodResponse
const data = response.data;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1