Definitelytyped: [@types/query-string]

Created on 1 Nov 2018  路  5Comments  路  Source: DefinitelyTyped/DefinitelyTyped

If you know how to fix the issue, make a pull request instead.

  • [ ] I tried using the @types/query-string package and had problems.
  • [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
  • [ ] I have a question that is inappropriate for StackOverflow. (Please ask any appropriate questions there).
  • [x] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see Definitions by: in index.d.ts) so they can respond.

    • Authors: @SamVerschueren @tkrotoff @huhuanming @MadaraUchiha @shssoichiro

Just a small improvement suggestion.

export interface OutputParams {
  [key: string]: string | string[] | undefined;
}

export function parse<T = OutputParams>(str: string, options?: ParseOptions): T;
export function parseUrl<T = OutputParams>(str: string, options?: ParseOptions): {url: string, query: T};

Usage example:

type MyQuery = {
  foo: string;
  bar: string;
}

const query = qs.parse<MyQuery>(location.search);

And the IDE can suggest the query object's properties.

image

Most helpful comment

It would be better to just do this

const query = qs.parse(location.search) as MyQuery;

All 5 comments

I've thought of that, but I'm a bit wary, especially given that you aren't really guaranteed to get the type you want out of it.

I suppose that having a sensible default is OK in this situation, though.

I'm OK with this.

It would be better to just do this

const query = qs.parse(location.search) as MyQuery;

It would be better to just do this

const query = qs.parse(location.search) as MyQuery;

This proposal will allow you to do both, if you so wish.

It's bad practice. See common mistakes.

getMeAT(): T: If a type parameter does not appear in the types of any parameters, you don't really have a generic function, you just have a disguised type assertion. Prefer to use a real type assertion, e.g. getMeAT() as number. Example where a type parameter is acceptable: function id(value: T): T;. Example where it is not acceptable: function parseJson(json: string): T;. Exception: new Map() is OK.

@SamVerschueren It's worth noting that that was written before default type parameters were a thing.

Was this page helpful?
0 / 5 - 0 ratings