Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with Typescript Interfaces- error: property does not exist

I built this interface

export interface UserInfo {
    success?: boolean,
    user?: User,
    employer?: Employer,
    hr?: Hr
}

Now when I do this

let data = await loginUser(loginData);
console.log(data.success);

loginUser method code:

import {createApi, fetchBaseQuery} from "@reduxjs/toolkit/query/react";
import {BASE_API_ENDPOINT, LOGIN_API_ENDPOINT} from "../../constants/apis";
import {LoginData, UserInfo} from "../../models/apis/UserData";

export const loginApi = createApi({
    reducerPath: 'loginReducer',
    baseQuery: fetchBaseQuery({ baseUrl: BASE_API_ENDPOINT }),
    endpoints: (builder) => ({
        loginUser: builder.mutation<UserInfo, LoginData> ({
            query: (data: LoginData) => ({
                    url: LOGIN_API_ENDPOINT,
                    method: "POST",
                    body: data
            }),
            transformResponse: (rawResult : UserInfo) => {
                return rawResult
            }
        })
    })
})
export const { useLoginUserMutation } = loginApi;

I get this error

Property 'success' does not exist on type '{ data: UserInfo; } | { error: FetchBaseQueryError | SerializedError; }'.

I am a newbie with typescript, and I want to access UserInfo object from { data: UserInfo; } but I am not being able to do so. Can anyone help?

like image 650
MadArk07 Avatar asked Apr 12 '26 11:04

MadArk07


2 Answers

This happens because the property "success" exists only on type UserInfo. Since it's a union type the compiler can't be sure whether the function returns a data object (with UserInfo type) or an error object (FetchBaseQueryError | SerializedError)

In order to access the success property of the response, you can firstly check if it exists

if("success" in data){
    console.log(data.success)
}

Read more about union types here:
https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types

like image 112
marius florescu Avatar answered Apr 14 '26 23:04

marius florescu


try use loginUser(loginData).unwrap() in component

like image 22
Александр Овчинников Avatar answered Apr 14 '26 23:04

Александр Овчинников



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!