Course contentsShow
← TypeScript
Lesson 857 of 1,79619. Template Literal TypesFree lesson

Type-Safe Query String Builders

Use template literals to construct query parameter strings with compile-time validation of parameter names.

Type-Safe Query String Builders

What you'll learn: How to use template literal types to build URL query strings with compile-time guarantees that parameter names are valid.


The Problem with Dynamic Query Strings

When building URLs with query parameters, you typically construct strings like ?userId=123&status=active. Without types, you might misspell parameter names or use parameters that don't exist on your API endpoint. Template literal types let you catch these errors at compile time.

Using Template Literals for Query Parameters

Imagine you have an API endpoint that accepts specific query parameters. You can model the allowed parameter names as a string literal union, then use template literals to construct type-safe query strings:

type SearchParams = 'userId' | 'status' | 'limit';

// Template literal type for query string format
type QueryString<K extends string> = `?${K}=${string}`;

// Valid usage
const validQuery: QueryString<SearchParams> = '?userId=123';
const anotherValid: QueryString<SearchParams> = '?status=active';

// Error: 'invalidParam' is not assignable
// const invalid: QueryString<SearchParams> = '?invalidParam=value';

Building Multi-Parameter Query Strings

You can extend this pattern to build more complex query strings with multiple parameters:

type ApiParams = 'page' | 'pageSize' | 'sortBy';

type MultiQuery<K extends string> = `?${K}=${string}&${K}=${string}`;

const query: MultiQuery<ApiParams> = '?page=1&pageSize=20';

Combining with Mapped Types

For maximum type safety, combine template literals with mapped types to generate all possible query parameter patterns:

type Filters = 'color' | 'size' | 'brand';

type FilterQuery = {
  [K in Filters]: `?${K}=${string}`;
}[Filters];

// FilterQuery = '?color=...' | '?size=...' | '?brand=...'

Key Takeaway: Template literal types transform URL query string building from error-prone string concatenation into a type-checked operation, ensuring you only reference valid parameter names at compile time.