A simple library to parse query params into proper types
npm install query-params-parser#query-params-parser
It is only focused on fixing the query/search params, the one you get from window.location.search or with the pattern ?param1=value1¶m2=100
npm i query-params-parser
``jsx
import parseParams from 'query-params-parser';
class ReferenceClass {
prop1 = '';
prop2 = 0;
prop3 = false;
prop4 = [];
}
/*
This class will work for the following uri:
home/page?prop1=value%20as%20string&prop2=100&prop3=no&prop4=item1,item2,item3
and will return the following object:
*/
``json`
{
"prop1": "value as string",
"prop2": 100,
"prop3": false,
"prop4": [
"item1",
"item2",
"item3"
]
}`jsx
console.log('result by class', parseParams(new ReferenceClass()))
// or the following with object declaration
console.log('result by object', parseParams({prop1: '', prop2: 0}))
`
jsx
import { stringToBoolean, parseByType} from 'query-params-parser';const byType = parseByType('item1, item2', [], ', ');
// byType will be ['item1', 'item2'];
const fromString = stringToBoolean('yes');
// fromString will be a boolean true;
``As javascript is a weak typed language, we cannot use the type definition to parse properties, so it is expecting a initialized object like a class with values defined to have typescript checking for its types.
examples of string values, they are not case sensitive
| section | examples |
|------------------|----------------------------------------------|
| values for true | "true", "yes" and "1" |
| values for false | "false", "no", "0", null, undefined, default |