Retrieve the stored information from a variable

Can anyone help me with a coding issue I'm facing? I have a constant called data, which contains two values - prediction and probability. What is the best way to access and retrieve both values?

type ML = {
    prediction: string;
    probability: number;
};

type GetUsersResponse = {
    data: ML[];
};


private async something(txt: string) {
        try {
            // 👇️ const data: GetUsersResponse
            const { data, status } = await axios.post<GetUsersResponse>(
                'http://127.0.0.1:5000/prediction',
                {
                    "text": txt
                },
            );

            console.log(JSON.stringify(data, null, 4));



            // 👇️ "response status is: 200"
            console.log('response status is: ', status);

            return data

        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.log('error message: ', error.message);
                return error.message;
            } else {
                console.log('unexpected error: ', error);
                return 'An unexpected error occurred';
            }
        }
    }

const data = something("This is a string")
// data looks like
// data = {
           "prediction": "Class 1",
           "probability": 0.612535596
           }

This is what I attempted but encountered errors:

data[0].prediction

TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'string | GetUsersResponse'.   Property '0' does not exist on type 'string | GetUsersResponse'.

data.prediction
TS2339: Property 'prediction' does not exist on type 'string | GetUsersResponse'.   Property 'prediction' does not exist on type 'string'.

data.data[0].probability
TS2339: Property 'data' does not exist on type 'string | GetUsersResponse'.   Property 'data' does not exist on type 'string'.

Answer №1

Before proceeding, ensure that your something function is capable of returning either a GetUserResponse or a string. It is important to first determine the type of the data before continuing.

If the type of data is a string:
    // Perform actions for error handling
else:
    Access the prediction from data.data[0]

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

Can the lib property in tsconfig.json override the target property?

Just starting out with Typescript, I have a query regarding the lib and target properties. Below is my tsconfig.json file: { "compilerOptions": { "target": "es5", "outDir": "./dist", "rootDir": "./src", "noEmitOnError": true, } } //index.ts consol ...

Tips for sidestepping the need for casting the class type of an instance

Looking to develop a function that can accept an argument containing a service name and return an instance of that particular service, all while ensuring proper typing. Casting the instance seems necessary in order to achieve the desired result. To illust ...

Creating or deleting multiple batches of entries in Firebase Realtime Database

I am currently utilizing Firebase real time database in the following way: createSoldLead(soldLead: SoldLeadModel): void { const soldLeadsReference = this.angularFireDatabase.list<SoldLeadModel>( `groups/${this.groupId}/soldLeads` ); ...

What is the best way to create unit tests for a React component using TypeScript?

I recently completed a small React project using TypeScript and decided to have it print numbers of li tags in the browser. During this process, I wanted to write unit tests that would test if the component created the HTML element . However, as someone ...

Navigate to a new tab using this.router.navigate

Is there a way to redirect the user to a specific page with ${id} opening in a new tab, after clicking a button in an angular material dialog box? I want to leave the dialog box open while querying the new page. Currently, the redirect happens but not in a ...

Error: Unable to locate module: 'fs' in 'node_modulesdotenvlib' - Next.js

I'm currently incorporating dotenv into my React project to use for API_URL. However, when I attempt to implement it in the index.js file within Next.js, I encounter the following error: Module not found: Can't resolve 'fs' in 'nod ...

TypeScript: Defining an Array Type within a Namespace or Module

Within a specific namespace, I have the following code: const operation1 = Symbol("operation1"); const operation2 = Symbol("operation2"); export interface Array<T> extends IConjable<T>, ISeqable<T> {} Array.prototype[op ...

Thoroughly verifying API responses in RTK Query with Zod schema

I am seeking to verify the API response I receive from a REST API by utilizing a Zod schema. As an illustration, I possess this user schema along with the corresponding API import { z } from 'zod'; import { createApi, fetchBaseQuery } from ' ...

What could be causing the excessive number of connections in my MongoDB instance?

This code snippet is crucial for my initial connection setup let cachedDbConnection: Db export async function establishDatabaseConnection(): Promise<{ db: Db }> { if (cachedDbConnection) { return { db: cachedDbConnection } } const client ...

Are fp-ts and Jest the perfect pairing for testing Option and Either types with ease?

When working with fp-ts, and conducting unit tests using Jest, I often come across scenarios where I need to test nullable results, typically represented by Option or Either (usually in array find operations). What is the most efficient way to ensure that ...

Show a modal when the axios request is finished

EDIT: After some exploration, I've shared the solution I found in case it helps others facing a similar issue. I'm currently working on building a reusable Bootstrap 5 modal child component within Vue3. The goal is to pass an ID as a prop from t ...

Incorrectly selecting an overload in a Typescript partial interface can lead to errors

My attempt to define an overload for my function using a Partial interface overloading is causing typescript to select the incorrect overload interface Args { _id: string; name: string; } interface Result { _id: string; name: string; } function my ...

Guide on utilizing a declaration within a third-party module

I have encountered an issue while using the fingerprintjs2 library, as the declaration provided in DefinitelyTyped seems incomplete and incompatible. In order to resolve this, I decided to create my own declaration within my project. However, I am facing ...

Tips for creating an observable in Angular 2

I'm having trouble declaring an observable and adding data to it in Angular 2. I've spent the last 5 hours trying to figure it out. Here's what I've attempted: this.products : Observable<array>; var object = {"item": item}; thi ...

Encountering a reference type error when using drag and drop with NextJS and react-dnd

When using react-dnd version 16 with TypeScript in Next.js, the refs within the return array of the useDrag and useDrop hooks are not compatible with LegacyRef. Interestingly, other platforms like Vite.Js handle this type assignment correctly. The same co ...

I am having trouble getting my custom colors to work with hover effects in Tailwind CSS

The code I have written is for a header component in Next.js with Typescript and Tailwind. I named it Header_2 to represent a component display in a library. Initially, the custom colors were not rendering as expected, but I managed to resolve the issue by ...

The .ts source file is mysteriously missing from the development tool's view after being deployed

When I work locally, I can see the .ts source files, but once I deploy them, they are not visible in any environment. Despite setting my sourcemap to true and configuring browserTargets for serve, it still doesn't work. Can someone help with this issu ...

Angular error: Unable to access the 'toLowerCase' property of an undefined value

I've been working on creating my own custom filter pipe by following the instructions in this video tutorial, but I encountered an error message stating, "Angular, TypeError: Cannot read property 'toLowerCase' of undefined". I have already i ...

In <R>, what does R represent when it is wrapped around an observer of type Observer<R>? Would it result in a Subscription, Function, or void?

The Angularfire2 project is in the process of adding a storage feature through a work-in-progress branch. This implementation includes two new files - an Observable class and a Factory function. Observable class export class FirebaseUploadTaskObservable& ...

React Typescript Mui causing `onBlur` event to trigger with every change occurring

I'm currently developing a front-end application using Typescript and React with MUI. The form code I have written is as follows: <TextField label="Password" value={this.state.password} placeholder="Choose a password" type="password" onC ...