@nuxtjs/axios 와 axios를 같이 쓸때 문제 feat. Typescript

Bewell·2021년 12월 28일
0
post-thumbnail

제목의 내용와 같이 대부분(?) nuxt프로젝트에서 @nuxtjs/axios와 axios를 함께 쓰게 되는데 몇가지 헷갈리는 몇가지가 있다.

1. plugins에서 호출하는 $axios는 '@nuxtjs/axios'인가 'axios'인가?

//	nuxt.config.js
...
  modules: {
	'@nuxtjs/axios'
  }
...

https://axios.nuxtjs.org/setup
@nuxtjs/axios 문서를 보면 npm 설치후 nuxt.config.js에 추가하도록 가이드 되어 있다. nuxt.config.js 추가를 통해 프로젝트 전역에서 사용할 수 있다

  1. 아래는 console에서 전역 $axios를 확인

  2. composition-api에서도 확인 가능

import { useContext } from '@nuxtjs/composition-api'
...
const { $axios } = useContext()	//	전역으로 접근 가능

결론 : 전역으로 설치된 모듈은 '@nuxtjs/axios'다



2.axios관련 Type 오류

//	/composables/useFetch.ts

import { AxiosError, AxiosResponse, AxiosRequestConfig } from 'axios'

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

const state = reactive<Result<T>>({
  response: null,
  error: null,
  loading: false
})

...
const result = await $axios.request({
  url,
  ...config,
  headers: {
    Authorization: `Bearer ${token}`
  }
})

state.response = result	//	<-- 여기서 type오류 발생!!
...

type오류 내용을 확인해 보면...(조금 길지만 자세히 보지 않으면 원인을 파악할 수 없기에 두 눈 크게 뜨고 👀)

const state: {
    response: {
        data: UnwrapRef<T>;
        status: number;
        statusText: string;
        headers: {
            [x: string]: string;
            "set-cookie"?: string[] | undefined;
        };
        config: {
            url?: string | undefined;
            method?: Method | undefined;
            ... 30 more ...;
            'axios-retry'?: {
                ...;
            } | undefined;
        };
        request?: any;
    } | null;
    error: {
        ...;
    } | null;
    loading: boolean;
}
Type 'AxiosResponse<any>' is not assignable to type '{ data: UnwrapRef<T>; status: number; statusText: string; headers: { [x: string]: string; "set-cookie"?: string[] | undefined; }; config: { url?: string | undefined; method?: Method | undefined; ... 30 more ...; 'axios-retry'?: { ...; } | undefined; }; request?: any; }'.
  The types of 'config.adapter' are incompatible between these types.
    Type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/@nuxtjs/axios/node_modules/axios/index").AxiosAdapter | undefined' is not assignable to type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/axios/index").AxiosAdapter | undefined'.
      Type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/@nuxtjs/axios/node_modules/axios/index").AxiosAdapter' is not assignable to type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/axios/index").AxiosAdapter'.
        Types of parameters 'config' and 'config' are incompatible.
          Type 'AxiosRequestConfig<any>' is not assignable to type 'AxiosRequestConfig'.
            Types of property 'transitional' are incompatible.
              Type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/axios/index").TransitionalOptions | undefined' is not assignable to type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/@nuxtjs/axios/node_modules/axios/index").TransitionalOptions | undefined'.
                Type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/axios/index").TransitionalOptions' is not assignable to type 'import("/Users/taewo/Taewoong-code/sentbe/BackOffceFront/node_modules/@nuxtjs/axios/node_modules/axios/index").TransitionalOptions'.
                  Types of property 'silentJSONParsing' are incompatible.
                    Type 'boolean | undefined' is not assignable to type 'boolean'.
                      Type 'undefined' is not assignable to type 'boolean'.ts(2322)

result$axios(=@nuxtjs/axios)의 타입이고, state.responseaxiosAxiosResponse타입에 매칭된다. 즉 비슷하지만 다른 타입인 것이다

결론적으로 as AxiosResponse를 통해 타입 단언을 해줄 수 있다.

0개의 댓글