Search

Parse, Don’t Validate 미니 과제 - After

// components/OrderPage.tsx function OrderPage() { const orderId = useOrderId(); // string 보장 const { data: order, isLoading, error } = useSuspenseQuery({ queryKey: ['order', orderId], queryFn: () => fetchOrder(orderId), }); // order는 Order 타입이 100% 보장됨 return ( <div> <h1>Order #{order.id}</h1> <OrderItems items={order.items} /> <OrderTotal total={order.total} /> <OrderStatus status={order.status} /> </div> ); }
TypeScript
복사
// hooks/useOrderId.ts function useOrderId(): string { const { orderId } = useParams(); if (!orderId) { throw new Error("Order ID is required"); } return orderId; } // api/orders.ts async function fetchOrder(orderId: string): Promise<Order> { const response = await http.get<Order>(`/api/orders/${orderId}`); if (!response.ok) { throw new Error(`Failed to fetch order: ${response.status}`); } return response.data }
TypeScript
복사
개선된 점:
orderId가 string임을 보장
order 객체의 모든 필드 타입 보장
방어적 코드 제거
비즈니스 로직과 검증 로직 분리