Skip to content

Conversation

@nnelgxorz
Copy link
Contributor

@nnelgxorz nnelgxorz commented Jul 26, 2022

What is it?

  • Feature / enhancement
  • Bug
  • Docs / tests

Description

Currently it is hard to type your useEndpoint call to your endpoint function.

Consider we have an onGet defined as an EndpointHandler<string>

Current behavior:

const onGet: EndpointHandler<string> = () => {
  return "Oh Qwik..."
}
const resource = useEndpoint(); // ResourceReturn<unknown>
const resource = useEndpoint<typeof onGet>(); // ResourceReturn<EndpointHandler<string>
const resource = useEndpoint<ReturnType<typeof onGet>>(); // ResouceReturn<string|void|null|undefined|Promise<string|void|null|undefined>>

Of course, you could type it yourself, ie useEndpoint<string>, but any changes to the return type of onGet do not trigger a type error for useEndpoint, making it a brittle solution. Also, you have the option of incorrectly type your useEndpoint call and not receiving an error until runtime. 😬

By adding a little helper type to the useEndpoint definition, we can check the generic, and if T extends EndpointHandler, extract the EndpointHandler type, otherwise use the original T type.

This allows developers to pass the relatively terse useEndpoint<typeof onGet>() and receive proper typing.

This gives the following behavior:

const onGet: EndpointHandler<string> = () => {
  return "Yay Qwik!"
}
const resource = useEndpoint(); // ResourceReturn<unknown>
const resource = useEndpoint<boolean>(); // ResourceReturn<boolean>
const resource = useEndpoint<null>(); // ResourceReturn<null>
//...etc
const resource = useEndpoint<typeof onGet>(); // ResourceReturn<string>

Checklist:

  • My code follows the developer guidelines of this project
  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • Added new tests to cover the fix / functionality

@nnelgxorz nnelgxorz marked this pull request as ready for review July 26, 2022 02:06
@manucorporat manucorporat merged commit d643fe8 into QwikDev:main Jul 26, 2022
@manucorporat
Copy link
Contributor

Thanks a lot for the PR!! love it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants