Typed Query Parameters
What You'll Learn
You'll learn how to create type-safe representations of URL query strings and build helper functions that prevent typos and ensure valid query parameter objects at compile time.
Why Query Parameters Need Types
Query parameters are typically passed as plain strings or loose objects, making them prone to typos and missing required fields. By typing your query parameters, you get autocomplete, compile-time validation, and self-documenting API contracts.
Think of it like a form with labeled fields versus a blank notepad—the structure guides you and prevents mistakes.
Creating Query Parameter Types
Define interfaces or type aliases that represent the expected query parameters:
// For a search endpoint
interface SearchQuery {
q: string;
page?: number;
limit?: number;
sort?: 'asc' | 'desc';
}
// For a filter endpoint
type ProductFilters = {
category: string;
minPrice?: number;
maxPrice?: number;
inStock?: boolean;
};
These types document what parameters are available and which are required.
Type-Safe Query Builder Functions
Create helper functions that accept typed objects and generate query strings:
function buildQueryString<T extends Record<string, string | number | boolean | undefined>>(
params: T
): string {
const entries = Object.entries(params)
.filter(([_, value]) => value !== undefined)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
return entries.length > 0 ? `?${entries.join('&')}` : '';
}
// Usage with type safety
const query: SearchQuery = {
q: 'typescript',
page: 2,
sort: 'desc'
};
const queryString = buildQueryString(query);
// "?q=typescript&page=2&sort=desc"
Now the compiler ensures you only pass valid parameter names and types.
Combining with fetch Wrappers
Integrate typed query parameters with your API functions:
interface ApiResponse {
results: string[];
total: number;
}
async function searchApi(query: SearchQuery): Promise<ApiResponse> {
const queryString = buildQueryString(query);
const response = await fetch(`https://api.example.com/search${queryString}`);
return response.json() as Promise<ApiResponse>;
}
// Type-safe usage
const results = await searchApi({
q: 'typescript',
page: 1,
sort: 'asc'
});
This prevents passing invalid parameters like { search: 'typescript' } when q is expected.
Key Takeaway: Typed query parameters transform error-prone string manipulation into compile-time-validated API calls, ensuring your URLs are always constructed correctly with autocomplete support and clear documentation.