Examining Typescript for a truthy value

When working with TypeScript, I am fetching data that has different types:

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

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

type ApiResponse = SuccessfulResponse | FailedResponse

After getting the data, I attempt to verify the response in this manner:

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

const data = response.data
// The compiler shows an error: Property 'data' does not exist on type 'SuccessfulResponse | FailedResponse.....

However, if I check for response.status === 0 it behaves as expected.

Answer №1

It would be beneficial for TypeScript to automatically infer the type based on the provided example. What version of TypeScript are you utilizing?
Nevertheless, I believe utilizing User type predicates would be a more robust approach in case the method of distinguishing between responses changes in the future:

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

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

// TypeScript now recognizes response as type GoodResponse
const data = response.data;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

What is the best way to access a shared object or variable across multiple files in TypeScript with Next.js?

I'm working with Next.js and have a single file containing the following code: export let counter = 0; In the first API route file /api/test1, I increment the counter by 5 like this: counter += 5; In the second API file /api/test2, I try to access t ...

Octokit: Unable to create multiple Labels at once

Issue with Creating Multiple Labels Example Code: Promise.all( srcRepoReq.data.map(async (label) => { const newLabel: ghLabel = { name: label.name, color: label.color, description: label.description, ...

Angular's observable data fail to show on the screen

I am facing an issue with passing the data of an Observable fetched via an API request to a component variable for display. I have been trying but unable to make it work successfully. Any assistance would be greatly appreciated. Here is my code. Thank you. ...

Typescript is failing to return nested types when attempting to return a nested object

My goal is for my function to return a nested type of Content, but it's not working even though the type that should be returned is known. Let's take a look at an example: type Content = { some: { extra: string; prop: number; ...

Guide on exporting Excel data using Angular and TypeScript

My project involves managing a table of information that includes fields for FirstName, LastName, PhoneNumber, Age, and Date. I've created a function that allows me to export the data to an Excel file, but I only want to export specific fields like Fi ...

Transferring information between components without relying on @Input and @Output properties

I am currently in need of a system that functions like a "shopping cart" for one component within my site. It will essentially be a list of user-generated needs collected while they browse. Although this system won't involve pricing or tax calculation ...

What is the best way to retrieve the year component from an observable ISO date string?

My angular component class is responsible for updating an interface with records of type Object, such as [{"examYear":"2001-01-02T00:00:00.000+00:00"},{...}], received from an Observable GET call to the backend service. The signature of ...

Troubleshooting issue with Vue3 - TS Custom State Management

Issue: I am facing a challenge in transferring data between two separate components - the main component and another component. Despite attempting to implement reactive State Management based on Vue documentation, the object's value remains unchanged ...

How can I use JavaScript to update the content inside HTML tags with a specific string?

I have a situation where I need to replace a string in two different ways Input: Parameters-->string, AnnotationName, input Case 1: And I should input <i>Annotaion</i> as <b>input</b> Output : { displayData: `And I should inp ...

Combining promises to handle the asynchronous promise received from this.storage.get() function

Struggling with managing asynchronous data retrieval from local storage in my Angular2/ionic2 app. The code snippet I'm using: request(args) { var headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

The label for the Angular radio button isn't displaying correctly

I encountered an issue with my component code where the radio button label does not display correctly when I try to edit it. The radio button value also does not get set correctly to the form value and always shows as "No". Despite adding [ngModel] & [valu ...

Using TypeScript to assign values to object properties

In myInterfaces.ts, I have defined a class that I want to export: export class SettingsObj{ lang : string; size : number; } Now I need to reference this class in another file named myConfig.ts in order to type a property value for an object called CO ...

A step-by-step guide on retrieving the present date and time using TypeScript

Details This is my first time creating a VSCode extension using TypeScript, and I am having trouble displaying the current date/time in an information message. My Attempts I have searched through VSCode key bindings for any references to date/time, as w ...

Tips on using class-validator @isArray to handle cases where only a single item is received from a query parameter

Currently, I am attempting to validate a request using class-validator to check if it is an array. The inputs are sourced from query parameters like this: /api/items?someTypes=this This is what my request dto resembles: (...) @IsArray() @IsEn ...

SystemJS is responsible for loading a multitude of files related to rxjs

After finding an example on the internet, I have created my own systemjs.config.js: (function (global) { System.config({ paths: { // paths serve as alias 'js:': 'js/', }, // map tells ...

Encountering errors 'LeftSegment' not found and 'infer' not found within the react-router directory in the node_modules folder

Currently, I am in the process of updating my application from react-router v3 to v6. At the moment, I have successfully installed react-router-dom v6.2.1 as well as react-router v6.2. Additionally, since I am using Typescript, I have also installed @types ...

When working in React, I often encounter the frustrating TypeError: Cannot read property 'content' of undefined error

Trying to customize a React project, I attempted to add a class to a div using the following code: <div className={styles.content}> In the case of deleting the Data Source, you will lose all configuration sett ...

The error message in Angular4 displays code that does not match the intended code to be executed

I am currently developing an application for a website that will handle simplex algorithms. One of my current tasks is to implement a feature that allows the user to input the number of coefficients and constraints, give them custom names, and then have th ...