Lesson 23 of 56
TypescriptWorking with JSON & External APIs
20 minutes
Course progress41%
Parsing JSON
interface User { id: number; name: string; }
const raw = `[{"id":1,"name":"Alice"}]`;
const users: User[] = .(raw);
Lesson 23 of 56
Typescript20 minutes
interface User { id: number; name: string; }
const raw = `[{"id":1,"name":"Alice"}]`;
const users: User[] = .(raw);
async function getUser(id: number): Promise<User> {
const resp = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!resp.ok) throw new Error('Network error');
const data = await resp.json();
return data as User;
}
zodnpm i zod
import { z } from "zod";
const UserSchema = z.object({ id: z.number(), name: z.string() });
const parsed = UserSchema.parse(await resp.json());