Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I type both the request body and the response body? #6759

Open
0xF5T9 opened this issue Jan 13, 2025 · 0 comments
Open

How do I type both the request body and the response body? #6759

0xF5T9 opened this issue Jan 13, 2025 · 0 comments

Comments

@0xF5T9
Copy link

0xF5T9 commented Jan 13, 2025

Describe the issue

I'm trying to type both the request body and the response body.

Example Code

// This code successfully typed the response body but I want to type the request body too.
const result = await backend.post<RawAPIResponse<ResponseData.RegisterResponseData>>(`register`, {
                email,
                username,
                password,
            });

Expected behavior

I expected something like this but it's not working:

const result = await backend.post<RequestBodyType, ResponseBodyType>(`register`, {
                email,
                username,
                password,
            });

I did some effort with search engines and found a snippet that actually works:

interface AuthResponse {
    token: string;
    token_type: string;

    access_token: string;
    access_token_expires_at: string;

    refresh_token: string;
    refresh_token_expires_at: string;
}

interface TBody {
    grant_type: string
    refresh_token: string
}

const t = async (): Promise<void> => {

    const data = await axios.post<AuthResponse, AxiosResponse<AuthResponse, TBody>, TBody>("theurl", {
        grant_type: 'kjkjk',
        refresh_token: "dddf",
    }, {
        headers: {
            Authorization: "dfdfds",
            "Content-Type": "application/json",
        },
    })

    const resu: AuthResponse = data.data

}

https://stackoverflow.com/questions/69541197/specify-axios-response-type-on-post-request-with-body
It works but I don't know why and I don't like it. I try to find the documentation about it but didn't find any. There is also a comment mentioned that this is not the "intended" way to use the library, which confuses me even more.

Axios Version

1.7.4

Adapter Version

No response

Browser

No response

Browser Version

No response

Node.js Version

No response

OS

No response

Additional Library Versions

No response

Additional context/Screenshots

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant