typed-url-search-params
v0.0.11
Published
**Zero-dependency | Type-safe | Modular**
Downloads
1,769
Readme
typed-url-search-params
Zero-dependency | Type-safe | Modular
typed-url-search-params is a lightweight TypeScript library for explicitly declaring and managing URL search parameters. It enables you to split responsibility across different parts of your application by creating multiple instances with their own parameter schemas, ensuring every URL parameter is documented and handled in a type-safe way.
Motivation
In large projects, URL search parameters can be used in an ad-hoc manner, leading to:
- Undocumented usage: Parameters appear and disappear with no central declaration.
- Unexpected behaviors: Implicit parameter handling can cause bugs and maintenance challenges.
- Poor developer experience: Lack of type hints and auto-completion increases the chance of mistakes.
This library solves these issues by enforcing explicit declaration of each supported parameter. With typed-url-search-params, you:
- Document your URL parameters: Every parameter is declared in a schema.
- Maintain separation of concerns: Create dedicated instances for different modules.
- Achieve full type-safety: Enjoy IDE autocompletion and compile-time checks.
Features
- Zero-dependency: No additional packages needed.
- Type-safe: Leverages TypeScript generics for precise parameter types.
- Modular: Multiple instances with separate schemas let different parts of your app manage their own parameters.
- Explicit: Every supported URL parameter is declared explicitly in a schema.
Installation
Install via npm:
npm install typed-url-search-paramsor
yarn add typed-url-search-paramsUsage
A very basic usage example:
import { TypedURLSearchParams, paramNumber, paramString, withDefault } from 'typed-url-search-params';
// Create an instance with an inlined schema
const params = new TypedURLSearchParams({
page: paramNumber,
search: paramString,
score: withDefault(paramNumber, 0)
});
// Retrieve parameters with full type safety and proper defaulting
const page = params.get("page"); // number | null
const search = params.get("search"); // string | null
const score = params.get("score"); // number (0 if not provided)In the example above we create a new instance of TypedURLSearchParams with a schema that defines three parameters:
page: A number parameter.search: A string parameter.score: A number parameter with a default value of0.
By default, if the parameter is not present in the URL, the value will be null.
If you want to provide a default value, you can use the withDefault helper function.
Then we retrieve the parameters using the get method, which returns the parameter value with the correct type.
Parameter names are type-checked, so you'll get autocompletion and type hints in your IDE.
You can define any parts of the schema separately, which is a bit more explicit:
// Define a custom parameter
const paramScore = withDefault(paramNumber, 0);
// Define a schema for a specific module or section of your app
const myParamsSchema = {
page: paramNumber, // Returns number | null
search: paramString, // Returns string | null
score: paramScore, // Returns number, defaulting to 0 if absent
};
// Create an instance using the schema
const params = new TypedURLSearchParams(myParamsSchema);
// Retrieve parameters with full type safety and proper defaulting
const page = params.get("page"); // number | null
const search = params.get("search"); // string | null
const score = params.get("score"); // number (0 if not provided)Flexibility showcase
You can define your own custom parameter types and reuse them across different schemas:
// Positive number parameter
const paramPositiveNumber: ParamDefinition<number> = {
parse: (value: string | null) => {
const parsed = paramNumber.parse(value);
return parsed !== null && parsed > 0 ? parsed : null;
},
}
// Positive number with 0 as default
const paramPositiveNumberOrZero = withDefault(paramPositiveNumber, 0)
// String processing example
const paramStringUpperCase: ParamDefinition<string> = {
parse: value => value ? value.toUpperCase() : null,
};
// One more string processing example
const paramStringLowerCase: ParamDefinition<string> = {
parse: value => value ? value.toLowerCase() : null,
};
const query = "?score=10&page=2&search=Hello&filter=Foo";
// Now use these custom parameters
const params = new TypedURLSearchParams({
score: paramPositiveNumber,
page: paramPositiveNumberOrZero,
search: paramStringUpperCase,
filter: paramStringLowerCase,
}, query);
const score = params.get("score"); // 10
const page = params.get("page"); // 2
const search = params.get("search"); // HELLO (uppered case)
const filter = params.get("filter"); // foo (lowered case)
const anotherQuery = = "?score=-15;
// Update the query
params.updateQuery(anotherQuery);
// Try get same values again
const score = params.get("score"); // null (-15 is not a positive number)
const page = params.get("page"); // 0 (value is not present, default is used)
const search = params.get("search"); // null
const filter = params.get("filter"); // null
// Expanding an existing schema
const anotherSchema = {
...myParamsSchema,
anotherParam: paramPositiveNumber,
someBoolean: paramBoolean,
}
API Reference
TypedURLSearchParams<Schema>
A class to manage URL search parameters based on a provided schema.
Constructor
new TypedURLSearchParams(schema: Schema, query?: string)schema: Schema
Type: An object mapping parameter names (keys) to their definitions (
ParamDefinition<T>).Description:
This object defines which URL parameters are supported, how they are parsed, and how they are serialized. Each parameter definition includes:- A
parsefunction: Converts the raw string value from the URL into a typed value. - An optional
defaultValue: Used when the parameter is missing in the URL.
Example:
const myParamsSchema = { page: paramNumber, // Parses to number or null search: paramString, // Parses to string or null score: withDefault(paramNumber, 0) // Parses to number, defaults to 0 if absent };- A
query?: string
Type:
string(optional)Description:
A query string representing the URL parameters (e.g.,"?page=1&search=hello"). If provided, theTypedURLSearchParamsinstance will parse this string according to the given schema. If omitted, the library automatically useswindow.location.search(if available), simplifying usage in browser environments. This means you can instantiate the class as follows:const params = new TypedURLSearchParams(myParamsSchema);and it will automatically parse the parameters from the current page's URL.
Or with a custom query string:
const params = new TypedURLSearchParams(myParamsSchema, myQueryString);
Contributing
Coming soon
License
Distributed under the MIT License. See LICENSE for more information.
