query-string icon indicating copy to clipboard operation
query-string copied to clipboard

Generic parse function

Open NoiRTvT opened this issue 5 years ago • 3 comments

So, want to used parse function by generic

export function parse<T = ParsedQuery>(query: string, options?: ParseOptions): T;

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

image

NoiRTvT avatar Apr 23 '20 21:04 NoiRTvT

I have also caught common case in practice. It would be really convenient to use this generic with static type checking.

pvburkov avatar Apr 24 '20 18:04 pvburkov

On DefinitelyTyped there is a lint rule to guard against this, and I would not recommend adding this as it hides an unsafe cast. There is nothing at all that guarantees that active be a boolean, or even exist, at runtime.

If you want to do this in your code, you can always do queryString.parse('...') as Some, which shows that you are casting. Adding a type parameter for this really only hides the as Some part, and makes it easier to miss the unsafety here...

It's the same with JSON.parse, it doesn't take a type parameter.

LinusU avatar May 07 '20 09:05 LinusU

@LinusU could you elaborate on why it would be unsafe? Could you not take the generic passed into the function & wrap a Partial around it?

jamiehaywood avatar Feb 05 '21 10:02 jamiehaywood