lukeed / lukeed/worktop

Add generic typing for Router.add handler

Open
#172 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
1.7k
Forks
41
PR merge metrics
No merged PRs in 30d

Description

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the Router.add declaration and implementation, using the generic signature shown in the issue as the requirement. Done means a Handler-style handler can be passed to Router.add without the reported type-assignment error.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
backend-api-design
Issue type
Feature
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.