Typescript in VUE

Bewell·2021년 12월 27일
0

1. axios request객체 config type


interface Result<K> {
	response: null | AxiosResponse<K>
  	error: null | ErrorType
  	loading: boolean
}

interface UseFetch {
	fetch: (url: string, config) => Promise<void>
	response: Ref<AxiosResponse | null>
	error: Ref<ErrorType | null>
	loading: Ref<boolean>
}
    
export default function useFetch<T> (): UseFetch {
    const state = reactive<Result<T>> {
      response: null,
      error: null,
      loading: false
    }
    
    const fetch = async (url: string, config = {}) => {
      ...
      await $axios.request({
        url,
        ...config
      })
      ...
    }
  
    return { ...toRefs(state), fetch }
}

  1. interface UseFetch의 config값에 type을 설정하라는 경고창이 뜬다
  2. config 값은 axios 요청 객체로 import { AxiosRequestConfig } from 'axios' type값을 조정할 수 있다
  3. node_modules/axios/index.d.ts 파일에 AxiosRequestConfig타입을 확인해 보면, 아래와 같이 다양한 값을 볼 수 있다
export interface AxiosRequestConfig<D = any> {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
  transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
  headers?: AxiosRequestHeaders;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: D;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: ((status: number) => boolean) | null;
  maxBodyLength?: number;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
  decompress?: boolean;
  transitional?: TransitionalOptions;
  signal?: AbortSignal;
  insecureHTTPParser?: boolean;
}
  1. 이 중 원하는 값에 대한 타입만 설정하고 싶다면
  2. 아래와 같이 Pick을 사용할 수 있다
type Options = Pick<AxiosRequestConfig, 'url' | 'method' | 'data' | 'params' | 'headers'>


6. 위와 같이 config에 타입이 잘 적용되었다

0개의 댓글