4 min read
Working with APIs and Typed Fetch
Prerequisites: Interfaces
fetch itself isn't generic — TypeScript doesn't know what shape an
API response has, so you assert or validate it against an interface
you define.
interface GitHubUser {
login: string;
public_repos: number;
}
async function getUser(username: string): Promise<GitHubUser> {
const response = await fetch(`https://api.github.com/users/${username}`);
return response.json() as GitHubUser;
}
Common mistakes
- Treating
as GitHubUseras a real runtime guarantee — it only tells the compiler what to assume; it doesn't check the actual response at runtime. For real validation, use a schema library (like Zod) that checks and produces the type together.