≪ Today I learned.
RSS購読
    公開日
    タグ
    TypeScript
    著者
    ダーシノ

    Open APIのスキーマ定義からメソッドごとにパスを取得する型

    type Paths = {
        '/items': {
            GET: unknown
            POST: unknown
        }
        '/items/:id': {
            GET: unknown
            PUT: unknown
            DELETE: unknown
        }
        '/others': {
            GET: unknown
        }
    }
    
    type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'
    type FilteredPathsBy<M extends Method> =  {
      [K in keyof Paths]: M extends keyof Paths[K] ? K : never
    }[keyof Paths]
    
    /**
     * HTTPメソッドごとにパスを取得する
     */
    type GetPaths = FilteredPathsBy<'GET'>
    //   ^? '/items' | '/items/:id' | '/others'
    type PostPaths = FilteredPathsBy<'POST'>
    //   ^? '/items'
    type PutPaths = FilteredPathsBy<'PUT'>
    //   ^? '/items/:id'
    type DeletePaths = FilteredPathsBy<'DELETE'>
    //   ^? '/items/:id'