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]) => {})
您也可以明确指定 key
和 fetcher
的参数类型。
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)
}