Skip to content

Type safety for data passed #2994

@carloschida

Description

@carloschida

I find it quite useful that I can annotate an AxiosReponse for type safety. Nevertheless, it's not the case for the data that I'm sending.

import axios, { AxiosResponse } from 'axios';

interface UserCreation {
    name: 'Alice';
}

interface User {
    id: string;
    name: string;
}

axios.post<UserCreation, AxiosResponse<User>>('/users', {})
// No compiler error

See it in this playground.

I'm supposed to pass a UserCreation-compliant object, but the compiler detects no errors since data?: any, despite having declared T=UserCreation.

I propose extending the annotations of data, and AxiosRequestConfig. For instance, instead of having:

// index.d.ts
export interface AxiosRequestConfig {
  data?: any;
  ...
}

post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;

We could have:

// index.d.ts
export interface AxiosRequestConfig<T = any>{
  data?: T;
  ...
}

post<T = any, R = AxiosResponse<T>>(url: string, data?: T, config?: AxiosRequestConfig<T>): Promise<R>;

Some other similarly small arrangements must be done, for which a PR will follow.

This situation is specially useful when dealing with APIs whose DTOs with CRUD operations vary for the same resource.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions