Skip to content

Commit 557a550

Browse files
Accept valueless parameters as true when using a boolean with types option (#410)
Co-authored-by: Sindre Sorhus <[email protected]>
1 parent a277921 commit 557a550

File tree

4 files changed

+23
-2
lines changed

4 files changed

+23
-2
lines changed

base.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,8 @@ export type ParseOptions = {
286286
});
287287
//=> {isAdmin: 'true', flagged: true, isOkay: false}
288288
```
289-
Note: The `'boolean'` type will also convert `'0'` and `'1'` string values to booleans.
289+
290+
Note: The `'boolean'` type also converts `'0'` and `'1'` to booleans, and treats valueless keys (e.g. `?flag`) as `true`.
290291
*/
291292
readonly types?: Record<
292293
string,

base.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,10 @@ function parseValue(value, options, type) {
309309
return type(value);
310310
}
311311

312+
if (type === 'boolean' && value === null) {
313+
return true;
314+
}
315+
312316
if (type === 'boolean' && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
313317
return value.toLowerCase() === 'true';
314318
}

readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ queryString.parse('?isAdmin=true&flagged=true&isOkay=0', {
217217
//=> {isAdmin: 'true', flagged: true, isOkay: false}
218218
```
219219

220-
Note: The `'boolean'` type will also convert `'0'` and `'1'` string values to booleans.
220+
Note: The `'boolean'` type also converts `'0'` and `'1'` to booleans, and treats valueless keys (e.g. `?flag`) as `true`.
221221

222222
- `'string'`: Parse `phoneNumber` as a string (overriding the `parseNumbers` option):
223223

test/parse.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,3 +592,19 @@ test('types option: boolean type accepts 1 and 0 as boolean values', t => {
592592
b: false,
593593
});
594594
});
595+
596+
test('types option: boolean type accepts an empty string as true', t => {
597+
t.deepEqual(
598+
queryString.parse('a&b', {
599+
parsebooleans: false,
600+
types: {
601+
a: 'boolean',
602+
b: 'boolean',
603+
},
604+
}),
605+
{
606+
a: true,
607+
b: true,
608+
},
609+
);
610+
});

0 commit comments

Comments
 (0)