1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

axiosでnullableなパラメーターを作成する

1
Posted at

達成したいこと

axiosでGETする際のパラメーターの要素を値があるときは指定する、ないときは指定しないようにしたい。

通常の書き方

const getSomeThing = async (param3?: string) => {
  // パラメーターを作成
  const params = {
    param1: 'param1',
    param2: 'param2',
    param3: param3
  }

  const res = await axios.get('url', { params })
  return res
}

このままだと引数で渡されたparam3がnullの時にaxiosのリクエストではparam3がnullで指定されてしまいます。
そもそもparam3がないときは指定しない方が予期せぬ挙動を防げると思います。

こう書けばいい

const getSomeThing = async (param3?: string) => {
  // レコード型にする
  const params: Record<string, string | undefined> = {
    param1: 'param1',
    param2: 'param2'
  }
  // param3があるときだけ指定される
  if (param3) {
    params.param3 = param3
  }

  const res = await axios.get('url', { params })
  return res
}

パラメーターをレコード型にします。
TypeScriptではRecord<Key, Type>となります。
Typeをstring or undefindにすることにより、後からパラメーターを付与することができます。

最後に

TypeScriptのレコード
https://typescriptbook.jp/reference/type-reuse/utility-types/record

axiosのパラメーター指定
https://axios-http.com/ja/docs/req_config

TypeScriptのレコード型いい感じに使っていきたいですね。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?