0
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 3 years have passed since last update.

RESTfullAPIのレスポンスデータへの型付

Last updated at Posted at 2021-09-25

TypeScriptのESLintのルールの1つ、@typescript-eslint/no-explicit-anyの対応の一環として、
各APIに対して割り当てられる汎用的な型の例をメモとして載せます。

※API側がPOSTとPATCHでもデータを返す事を想定しています。

最終的にはこんな感じ


type PickPartial<T, D extends keyof T> = Partial<Pick<T, D>> & Omit<T, D>

type BaseApi<
  T, // 基本となるデータの型
  O extends keyof T, // Optional Keys
  KS extends string, // Key Singular
  KP extends string // Key Prural
> = {
  data: T
  optionalData: PickPartial<T, O>
  index: { [key in KP]: T[] }
  get: { [key in KS]: T }
  post: { [key in KS]: T }
  patch: { [key in KS]: T }
}

使用例

上記で定義したBaseApiの型を使って、~.d.tsファイルなどでUserの型を定義

declare namespace ApiResponse {
  type User = {
     id: number
     name: string
     email: string
     age: number
     admin: boolean
   }
}

export type User = Pick<
    BaseApi<
     ApiResponse.User,
     "email" | "age",
     "user",
     "users",
    >,
    "data" | "index" | "get" | "post" | "patch"
>


例えば、Userの一覧を取得するAPIで
axiosを用いて通信する関数の戻り値に対して、以下のように使える。


getUsers(): Promise<AxiosResponse<User['index']>> {
...省略
}
// response.dataがこのようになる場合に有効
//{ users: [ { id: 1, name: "name", email: "email", age: 20, admin: true} ...省略 ] }
0
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
0
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?