hono icon indicating copy to clipboard operation
hono copied to clipboard

`c.req.query` should support generics

Open kahosan opened this issue 2 years ago • 3 comments

What is the feature you are proposing?

Hey

Currently, the type of query is Record<string, string>. However, when I have a predefined type, such as:

interface A {
  userId: string
  type: 'all' | 'post'
}

I hope the type of query can be changed to A, so that I can directly use c.req.query<A>() to pass parameters to functions that accept type A.

Perhaps its type definition is like this:

query<T = Record<string, string | undefined>>(): T

kahosan avatar Oct 31 '23 05:10 kahosan

Hi @kahosan,

This seems to be a good suggestion. However, inferring types perfectly is difficult for me, or it might be impossible.

For example, this issue

I'll continue to investigate it. Thanks.

yusukebe avatar Oct 31 '23 13:10 yusukebe

right, I gave it a try.

When string exists, literals will be directly inferred as string instead of the designated literal type. Moreover, different keys with distinct literal types will be merged.

For example:

type T = {
  a: 'a'
  b: 'b'
}

const type = query<T>('a')
//    ^? type: 'a' | 'b'

type T = {
  a: string
  b: 'b'
}

const type = query<T>('a')
//    ^? type: string

This seems to be a problem with TypeScript, do we have a way to infer the type of key?

kahosan avatar Nov 01 '23 03:11 kahosan

This seems to be a problem with TypeScript, do we have a way to infer the type of key?

Hmm. I'll keep to investigating it, but it may be impossible for TypeScript (TypeScript is sometime troublesome).

yusukebe avatar Nov 01 '23 14:11 yusukebe