[query-string] Make types more accurate (#29395)

* [query-string] Make types more accurate

* Update index.d.ts

* Fix ts errors

* Fix linter errors

* Fix types and make tests more accurate

* Fix linter errors
This commit is contained in:
Sean Zhu 2018-10-10 13:08:52 -07:00 committed by Andy
parent 3052704412
commit e174f81551
2 changed files with 26 additions and 12 deletions

View File

@ -13,13 +13,21 @@ export interface ParseOptions {
decode?: boolean;
}
export interface InputParams {
[key: string]: any;
}
export interface OutputParams {
[key: string]: string | string[] | undefined;
}
/**
* Parse a query string into an object.
* Leading ? or # are ignored, so you can pass location.search or location.hash directly.
*/
export function parse(str: string, options?: ParseOptions): any;
export function parse(str: string, options?: ParseOptions): OutputParams;
export function parseUrl(str: string, options?: ParseOptions): {url: string, query: any};
export function parseUrl(str: string, options?: ParseOptions): {url: string, query: OutputParams};
export interface StringifyOptions {
strict?: boolean;
@ -30,7 +38,7 @@ export interface StringifyOptions {
/**
* Stringify an object into a query string, sorting the keys.
*/
export function stringify(obj: object, options?: StringifyOptions): string;
export function stringify(obj: InputParams, options?: StringifyOptions): string;
/**
* Extract a query string from a URL that can be passed into .parse().

View File

@ -19,20 +19,26 @@ import * as queryString from 'query-string';
result = queryString.stringify({ foo: 'bar' }, { strict: false, encode: false });
}
// For each section below, the second line ensures the real answer is of the declared
// type. You can find the real answer by running the first line of each section.
// parse
{
let fooBar: { foo: 'bar' };
fooBar = queryString.parse('?foo=bar');
fooBar = queryString.parse('#foo=bar');
fooBar = queryString.parse('?foo=bar%20baz', { decode: true });
let fooBar = queryString.parse('?foo=bar');
fooBar = {foo: "bar"};
let fooBarBaz: { foo: ['bar', 'baz'] };
fooBarBaz = queryString.parse('&foo=bar&foo=baz');
let fooBarBaz1 = queryString.parse('&foo=bar&foo=baz');
fooBarBaz1 = { foo: [ 'bar', 'baz' ] };
let fooBarBaz2 = queryString.parse('&foo[]=bar&foo[]=baz', {arrayFormat: 'bracket'});
fooBarBaz2 = { foo: [ 'bar', 'baz' ] };
}
// extract
{
let result: string;
result = queryString.extract('http://foo.bar/?abc=def&hij=klm');
result = queryString.extract('http://foo.bar/?foo=bar');
let result1 = queryString.extract('http://foo.bar/?abc=def&hij=klm');
result1 = 'abc=def&hij=klm';
let result2 = queryString.extract('http://foo.bar/?foo=bar');
result2 = 'foo=bar';
}