// 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
복사
개선된 점:
•
•
•
•
