koajs / bodyparser

Koa body parsing middleware
MIT License
1.3k stars 116 forks source link

[fix] Type disagreement between `koa-body` and `@types/koa-bodyparser` #150

Closed maslade closed 1 year ago

maslade commented 1 year ago

Describe the bug

Node.js version: 16

OS version: OSX 11.6.4

Description: Types are incompatible between these two projects. From some investigating, it looks like this has been a recurring off-and-on problem that was reintroduced via the DefinitelyTyped project about a week ago.

I started a discussion on that project board but it's tumbleweeds at the moment, so I thought I'd raise it here as well, but feel free to close if this is the wrong place. I'm mostly looking for guidance and would be happy to submit a PR to fix.

https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/62237

Actual behavior

Type error:

#17 221.7 node_modules/@types/koa-bodyparser/index.d.ts(25,9): error TS2717: Subsequent property declarations must have the same type.  Property 'body' must be of type 'any', but here has type 'Record<string, unknown> | undefined'.

Expected behavior

No type error between latest versions of koa-body and koa-bodyparser.

Code to reproduce

// Step 1. `npm install koa-body koa-bodyparser @types/koa-bodyparser@latest typescript`
// Step 2: `npx tsc example.ts`
import {} from 'koa-body';

Checklist

megakoresh commented 1 year ago

This should definitely be fixed, even if using both at the same time is not recommended, this is very intrusive behavior and a breaking change. The body type should be a generic that can be modified in user code. And this kind of thing should not be allowed IMO, this is not worthwhile change to break backwards compatibility and require users to update their code.

alifarooq0 commented 1 year ago

Running into the same issue. Any workaround for this?

3imed-jaberi commented 1 year ago

Hey guys, I would mention that I have re-created the module with TS so no need to @types/koa-bodyparser in the future (once the PR merged).

For quick solution about the typing behave, you can override the request signature like this

declare module "koa" {
    interface Request {
        body?: Record<string, unknown>; // BTW, you can override it to any type you want ... 
        rawBody: string;
    }
}