hapijs / hapijs/hapi

[TS] Defining the handler and the return type

Open
#4,479 2 comments 1 reaction 0 assignees View on GitHub
support
Dominant language
JavaScript
Stars
14.8k
Forks
1.4k
Avg merge
22d 3h
Merged PRs (30d)
1

Description

### Runtime

Node

### Runtime version

18

### Module version

21.3.3

### Used with

standalone

### Any other relevant information

_No response_

### How can we help?

I would like the handler to explicitly return the DataResultObject type (my object type), the handler type declaration in Hapi looks like this:

```js
export namespace Lifecycle {
/**
* Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps:
* extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecycle methods
* provided by the developer and executed by the framework.
* Each lifecycle method is a function with the signature await function(request, h, [err]) where:
* * request - the request object.
* * h - the response toolkit the handler must call to set a response and return control back to the framework.
* * err - an error object available only when the method is used as a failAction value.
*/
type Method<
Refs extends ReqRef = ReqRefDefaults,
R extends ReturnValue = ReturnValue
> = (
this: MergeRefs['Bind'],
request: Request,
h: ResponseToolkit,
err?: Error | undefined
) => R;
```

So I declare the route object like this:

```ts
const poemsRoutings: ServerRoute[] = [
{
method: "GET",
path: "/api/poems/pages/count",
options: {
handler: poems.getPoemsPagesCountHandler,
auth: {
mode: "try"
}
}
},
```

and the environment (vscode) correctly develops this type, showing that my type will be returned:

![image](https://github.com/hapijs/hapi/assets/17312717/ef0cc268-7917-41cb-9159-b05f23af9ee7)

But at the same time, I get a TS compilation error (which you can also see in the screenshot) that reads:

`Generic type 'ServerRoute' requires between 0 and 1 type arguments.ts(2707)`

How to do this correctly?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.