Created
August 3, 2026 23:40
-
-
Save imroca/fb46cd7cbf96785111e9a25637a83938 to your computer and use it in GitHub Desktop.
Building a type-safe fetch in #typescript by @mattpocockuk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const get = async ( | |
| url: string, | |
| input: Record<string, string> | |
| ) => { | |
| return fetch( | |
| `${url}?${new URLSearchParams(input).toString()}` | |
| ); | |
| }; | |
| export const post = async ( | |
| url: string, | |
| input: Record<string, string> | |
| ) => { | |
| return fetch(url, { | |
| method: "POST", | |
| body: JSON.stringify(input), | |
| }); | |
| }; | |
| type CreateAPIMethod = < | |
| TInput extends Record<string, string>, | |
| TOutput | |
| >(opts: { | |
| url: string; | |
| method: "GET" | "POST"; | |
| }) => (input: TInput) => Promise<TOutput>; | |
| const createAPIMethod: CreateAPIMethod = | |
| (opts) => (input) => { | |
| const method = opts.method === "GET" ? get : post; | |
| return ( | |
| method(opts.url, input) | |
| // Imagine error handling here... | |
| .then((res) => res.json()) | |
| ); | |
| }; | |
| /** | |
| * You can reuse this function as many times as you | |
| * like to create all your API methods! | |
| */ | |
| const getUser = createAPIMethod< | |
| { id: string }, // The input | |
| { name: string } // The output | |
| >({ | |
| method: "GET", | |
| url: "/user", | |
| }); | |
| getUser({ id: 123 }); // All type safe! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment