You can define custom parameter types by creating an object with encode and decode functions. The library provides several built-in types and utility functions to assist with this.
Built-in Param Types Behavior
| value | encoding | description |
|---|
null | ?foo | Encoded as a key with no value |
"" | ?foo= | Encoded as an empty string |
undefined | ? | Removed from the URL |
Common Built-in Types
| Param | Type | Example Decoded | Example Encoded |
|---|
StringParam | string | 'foo' | ?qp=foo |
NumberParam | number | 123 | ?qp=123 |
ObjectParam | { key: string } | { foo: 'bar', baz: 'zzz' } | ?qp=foo-bar_baz-zzz |
ArrayParam | string[] | ['a','b','c'] | ?qp=a&qp=b&qp=c |
JsonParam | any | { foo: 'bar' } | ?qp=%7B%22foo%22%3A%22bar%22%7D |
DateParam | Date | Date(2019, 2, 1) | ?qp=2019-03-01 |
DateTimeParam | Date | Date(2019, 2, 1) | ?qp=2019-02-28T22:00:00.000Z |
BooleanParam | boolean | true | ?qp=1 |
NumericObjectParam | { key: number } | { foo: 1, bar: 2 } | ?qp=foo-1_bar-2 |
DelimitedArrayParam | string[] | ['a','b','c'] | ?qp=a_b_c |
DelimitedNumericArrayParam | number[] | [1, 2, 3] | ?qp=1_2_3 |
Enum Parameters
Use createEnumParam for single values or createEnumArrayParam / createEnumDelimitedArrayParam for arrays to restrict decoded output to a specific list of allowed values.
import { createEnumParam, createEnumArrayParam } from 'serialize-query-params';
// String enum: values other than 'asc' or 'desc' decode as undefined
const SortOrderEnumParam = createEnumParam(['asc', 'desc']);
type Color = 'red' | 'green' | 'blue';
// Array enum: values other than allowed colors decode as undefined
const ColorArrayEnumParam = createEnumArrayParam<Color[]>(['red', 'green', 'blue']);
import {
encodeDelimitedArray,
decodeDelimitedArray
} from 'serialize-query-params';
/** Uses a comma to delimit entries. e.g. ['a', 'b'] => qp?=a,b */
const CommaArrayParam = {
encode: (array: string[] | null | undefined): string | undefined =>
encodeDelimitedArray(array, ','),
decode: (arrayStr: string | string[] | null | undefined): string[] | undefined =>
decodeDelimitedArray(arrayStr, ',')
};