The fastest way to start using Better Fetch is to import the betterFetch function.
You can define the response type using generics or use a schema that supports Standard Schema (recommended).
fetch.ts
import { betterFetch } from '@better-fetch/fetch';// Using generic typeconst { data, error } = awaitbetterFetch<{userId: string;id: number;title: string;completed: boolean;}>("https://jsonplaceholder.typicode.com/todos/1");// Using a Standard Schema validator (for example, zod)import { z } from 'zod'; // or your preferred Standard Schema compliant libraryconst { data: todos, error: todoError } = awaitbetterFetch("https://jsonplaceholder.typicode.com/todos/1", {output: z.object({userId: z.string(),id: z.number(),title: z.string(),completed: z.boolean(), }) });
Hover over the data object to see the type
Make sure strict mode is enabled in your tsconfig when using schema validations.
Better fetch by default returns a Promise that resolves to an object of data and error but if you pass the throw option, it will return the parsed response data only.
You can throw errors instead of returning them by passing the throw option.
If you pass the throw option, the betterFetch function will throw an error. And instead of returning data and error object it'll only the response data as it is.
fetch.ts
import { createFetch } from '@better-fetch/fetch';import { z } from 'zod';const$fetch =createFetch({baseURL: "https://jsonplaceholder.typicode.com",throw: true,});constdata = await$fetch<{userId: number;}>("https://jsonplaceholder.typicode.com/todos/1");