Loading Depth Study
Preparing your workspace
External data should be treated as untrusted until it has been checked and represented with appropriate types.
TypeScript types do not automatically validate data received from an API, database, or user input at runtime. A response may not match the type you expected. This means developers should separate compile-time types from runtime validation. API response interfaces can describe the expected structure, while validation libraries or custom checks can verify actual data. Using unknown instead of any is often safer when the structure has not yet been verified.
A frontend may expect a course API to return an ID, title, and lessons, but the server response should still be checked before the application trusts it.
interface CourseResponse {
id: string;
title: string;
lessons: number;
}
async function loadCourse(): Promise<CourseResponse> {
const response = await fetch('/api/course');
if (!response.ok) {
throw new Error('Failed to load course');
}
const data: unknown = await response.json();
if (
typeof data === 'object' &&
data !== null &&
'id' in data &&
'title' in data &&
'lessons' in data
) {
return data as CourseResponse;
}
throw new Error('Invalid course response');
}The function loads external data, checks that the response has the expected basic fields, and then returns it as a CourseResponse.