Is it possible to set a base type in SWR using TypeScript? #3016
Unanswered
Red-Killer
asked this question in
Q&A
Replies: 1 comment 1 reply
-
You can wrap useSWR and then import that where needed: import useSWR, { SWRResponse } from "swr";
interface DefaultResponse {
success: boolean;
message?: string;
}
export const useMySWR = <T>(key: string): SWRResponse<DefaultResponse & T> => useSWR(key); in your component: const { data } = useMySWR<SomeOtherType>("/somepath") |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I want to ensure that when using
useSWR
in Next.js, the returneddata
always contains two specific fields:success: boolean
message?: string
This should be the default behavior, without the need to explicitly define
useSWR<BaseResponse>("/somepath")
every time. Additionally, it should be extendable if another type is passed.For example:
The
data
would have the following structure by default:However, when you extend with another type, like this:
The resulting
data
type would look like:Is something like that possible?
Beta Was this translation helpful? Give feedback.
All reactions