最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Working with Typescript Interfaces- error: property does not exist - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Sep 1, 2021 at 12:45 jps 22.6k16 gold badges88 silver badges106 bronze badges asked Sep 1, 2021 at 12:33 MadArk07MadArk07 431 gold badge3 silver badges6 bronze badges 5
  • 1 This looks like a bad method typing. Can you also show us the code of loginUser()? – Mihai Paraschivescu Commented Sep 1, 2021 at 12:36
  • Does loginUser api returns { data: UserInfo; } as response? – Rahul Kumar Commented Sep 1, 2021 at 12:40
  • I have added the loginUser method in the description – MadArk07 Commented Sep 1, 2021 at 12:41
  • The error indicates that the data you are working with may not be a success result. In this case, you would need to narrow the type with a type guard. – crashmstr Commented Sep 1, 2021 at 12:49
  • Console.log your response or check it on postman what response you get – Rahul Kumar Commented Sep 1, 2021 at 12:50
Add a ment  | 

3 Answers 3

Reset to default 5

This happens because the property "success" exists only on type UserInfo. Since it's a union type the piler 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/docs/handbook/unions-and-intersections.html https://www.typescriptlang/docs/handbook/2/everyday-types.html#union-types

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

The actual issue is found inside the transformResponse function, and how it 'tunnels' the response data further.

transformResponse: (rawResult : UserInfo) => {
  return rawResult
}

rawResult most likely is not of type UserInfo, but a { data: UserInfo }. And that's exactly what you see in the error you get.

So to fix it, the function should look like this:

transformResponse: (rawResult: { data: UserInfo }) => {
  return rawResult.data
}

And then you code should work as expected, without any other ifs.

let data = await loginUser(loginData);
console.log(data.success);
发布评论

评论列表(0)

  1. 暂无评论