LoginSignup
70
39

More than 3 years have passed since last update.

型を明確にしながらaxiosを使う

Posted at

この記事では、APIへの問い合わせ時にJSONの各項目の型を明確にしながらaxiosを利用してみます。
get, postなどの基本的なメソッドに絞った内容です。)

JSみたいに利用する

JSと同じようにaxiosを利用すると、成功時のレスポンス・エラー時のレスポンスそれぞれがanyになります。

import axios from 'axios'

axios.post(
  'https://reqres.in/api/register',
  {
    email: 'eve.holt@reqres.in',
    password: 'pistol',
  }
)
.then(res => {
  // res.dataはanyになる
  console.info('token: ' + res.data.token)
})
.catch((e) => {
  if (e.response !== undefined) {
    // e.response.dataはanyになる
    console.error(e.response.data.error)
  }
})

型の情報を伝える

インターフェイスを定義して、ジェネリクスで伝えてあげることで応答に関する型を明確にすることができます。
定義を見る感じでは、リクエストデータについてはジェネリクス経由で型情報を伝えることができないみたいなので、注釈付きで変数を作り、それを引数に渡します。(他に良い方法があれば是非教えていただけると!)

import axios, { AxiosError } from 'axios'

interface IPostRequest {
  email: string
  password: string
}

interface IPostResponse {
  id: number
  token: string
}

interface IErrorResponse {
  error: string
}

// 項目に欠けがあった場合でもエラーが出るよう外部で定義
const requestData: IPostRequest = {
  email: 'eve.holt@reqres.in',
  password: 'pistol'
}

// サーバからの応答の形式を渡す
axios.post<IPostResponse>(
  'https://reqres.in/api/register',
  requestData,
)
.then(res => {
  // res.data.tokenはstring
  console.info('token: ' + res.data.token)
})
// エラー応答の構造を明示する
.catch((e: AxiosError<IErrorResponse>) => {
  if (e.response !== undefined) {
    // e.response.data.errorはstring
    console.error(e.response.data.error)
  }
})

デモ
https://codesandbox.io/s/typed-axios-0lgsy?file=/src/index.ts

おわりに

次の各メソッドで、レスポンスの形式については前述の内容と同じ指定方法でTypeScriptの恩恵を受けられそうです。
request, get, delete, head, options, post, put, patch

70
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
70
39