Created
August 17, 2025 01:56
-
-
Save peakh/c4a60c92095c69a18990c97ae27dcfbd to your computer and use it in GitHub Desktop.
A fetch function in TypeScript with a type parameter for proper typing.
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 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; | |
| } |
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
| // 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