Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generic typing for Router.add handler #172

Open
hariria opened this issue Dec 3, 2022 · 0 comments
Open

Add generic typing for Router.add handler #172

hariria opened this issue Dec 3, 2022 · 0 comments

Comments

@hariria
Copy link

hariria commented Dec 3, 2022

Problem

I want to have strong typing but currently the Router class' add function has a signature like so:

export declare class Router {
	add<T extends RegExp>(method: Method, route: T, handler: Handler<Params>): void;
	...
}

The problem is that handler has a signature like so:

export type Handler<P extends Params = Params> = (req: ServerRequest<P>, res: ServerResponse) => Promisable<Response|void>;

Because the Router's add function is Handler<Params> and not Handler<P extends Params = Params>, this prevents people from adding handlers to the Router.add function that implement a type P that extends Params

Solution

would be nice to change to something like

	add<T extends RegExp, P extends Params = Params>(method: Method, route: T, handler: Handler<P>): void;

Context

The reason why is because atm when I do something like

import { listen, Router } from 'worktop';

export interface VerifyParams extends Params {
  address: string;
  anotherParam: string;
}

export const verify: Handler<VerifyParams> = async (
  req,
  res,
) => {
  const { address, anotherParam } = req.params;
  const isVerified = address === 'hi' && anotherParam === 'also hi';
  res.send(200, { isVerified }, { 'cache-control': 'private,max-age=30' });
};

const API = new Router();
API.add<RegExp>('GET', /verify/, verify);

this throws the error

Argument of type 'Handler<VerifyParams>' is not assignable to parameter of type 'Handler<Params>'.
  Type 'Params' is missing the following properties from type 'VerifyParams': address, anotherParam
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

No branches or pull requests

1 participant