跳至內容
文件
TypeScript

TypeScript

SWR 對於使用 TypeScript 編寫的應用程式非常友善,開箱即具有型別安全。

基本用法

預設情況下,SWR 也會從 key 推斷 fetcher 的參數類型,因此您可以自動擁有偏好的類型。

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

  • 內聯訂閱函式,並使用 SWRSubscriptionOptions 手動指定 next 的類型。
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 宣告訂閱函式
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)
}