Skip to content

Instantly share code, notes, and snippets.

@peakh
Created August 17, 2025 01:56
Show Gist options
  • Select an option

  • Save peakh/c4a60c92095c69a18990c97ae27dcfbd to your computer and use it in GitHub Desktop.

Select an option

Save peakh/c4a60c92095c69a18990c97ae27dcfbd to your computer and use it in GitHub Desktop.
A fetch function in TypeScript with a type parameter for proper typing.
export default async function strictFetch<T>(url: string, options?: RequestInit): Promise<T> {
const res = await fetch(url, options);
const json = await res.json() as T;
return json;
}
// Example usage.
type Result = {
name: string;
description: string;
};
const request = await strictFetch<Result>("https://example.com");
console.log(request.name);
// Example output: "Josh"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment