コンテンツへスキップ
ドキュメント
TypeScript

TypeScript

SWRはTypeScriptで記述されたアプリケーションにフレンドリーで、すぐに型安全性が利用できます。

基本的な使用方法

デフォルトでは、SWRはfetcherの引数の型をkeyから自動的に推論するため、好ましい型を自動的に使用できます。

useSWR

// `key` is inferred to be `string`
useSWR('/api/user', key => {})
useSWR(() => '/api/user', key => {})
 
// `key` will be inferred as { a: string; b: { c: string; d: number } }
useSWR({ a: '1', b: { c: '3', d: 2 } }, key => {})
useSWR(() => ({ a: '1', b: { c: '3', d: 2 } }), key => {})
 
// `arg0` will be inferred as string.  `arg1` will be inferred as number
useSWR(['user', 8], ([arg0, arg1]) => {})
useSWR(() => ['user', 8], ([arg0, arg1]) => {})

keyfetcherの引数の型を明示的に指定することもできます。

import useSWR, { Fetcher } from 'swr'
 
const uid = '<user_id>'
const fetcher: Fetcher<User, string> = (id) => getUserById(id)
 
const { data } = useSWR(uid, fetcher)
// `data` will be `User | undefined`.

デフォルトでは、スローされたエラーfetcher関数内でany型になります。型は明示的に指定することもできます。

const { data, error } = useSWR<User, Error>(uid, fetcher);
// `data` will be `User | undefined`.
// `error` will be `Error | undefined`.

useSWRInfinite

swr/infiniteについても、自動的な型推論に依存するか、自分で型を明示的に指定することができます。

import { SWRInfiniteKeyLoader } from 'swr/infinite'
 
const getKey: SWRInfiniteKeyLoader = (index, previousPageData) => {
  // ...
}
 
const { data } = useSWRInfinite(getKey, fetcher)

useSWRSubscription

  • インラインのsubscribe関数と、nextの型をSWRSubscriptionOptionsを使って手動で指定します。
import useSWRSubscription from 'swr/subscription'
import type { SWRSubscriptionOptions } from 'swr/subscription'
 
const { data, error } = useSWRSubscription('key', 
  (key, { next }: SWRSubscriptionOptions<number, Error>) => {
  //^ key will be inferred as `string`
  //....
  })
  return {
    data,
    //^ data will be inferred as `number | undefined`
    error
    //^ error will be inferred as `Error | undefined`
  }
}
  • SWRSubscriptionを使ってsubscribe関数を宣言します。
import useSWRSubscription from 'swr/subscription'
import type { SWRSubscription } from 'swr/subscription'
 
/** 
 * The first generic is Key
 * The second generic is Data
 * The Third generic is Error
 */
const sub: SWRSubscription<string, number, Error> = (key, { next }) => {                         
  //......
}
const { data, error } = useSWRSubscription('key', sub)

ジェネリクス

dataの型を指定するのは簡単です。デフォルトでは、fetcherの戻り値の型(準備完了でない状態ではundefined)がdata型として使用されますが、パラメーターとして渡すこともできます。

// 🔹 A. Use a typed fetcher:
// `getUser` is `(endpoint: string) => User`.
const { data } = useSWR('/api/user', getUser)
 
// 🔹 B. Specify the data type:
// `fetcher` is generally returning `any`.
const { data } = useSWR<User>('/api/user', fetcher)

SWRの他のオプションに型を追加する場合は、それらの型を直接インポートすることもできます。

import useSWR from 'swr'
import type { SWRConfiguration } from 'swr'
 
const config: SWRConfiguration = {
  fallbackData: "fallback",
  revalidateOnMount: false
  // ...
}
 
const { data } = useSWR<string[]>('/api/data', fetcher, config)

ミドルウェアの型

カスタムミドルウェアに型を追加するのに役立つ追加の型定義があります。

import useSWR, { Middleware, SWRHook } from 'swr'
 
const swrMiddleware: Middleware = (useSWRNext: SWRHook) => (key, fetcher, config) => {
  // ...
  return useSWRNext(key, fetcher, config)
}