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

readBody has a default returnType of Promise<any> instead of Promise<unknown> #386

Closed
rijkvanzanten opened this issue May 16, 2023 · 1 comment
Labels
good first issue Good for newcomers

Comments

@rijkvanzanten
Copy link

Environment

Node v20.2.0
h3 1.6.6
typescript 5.0.4

Reproduction

import { eventHandler, readBody, sendNoContent } from "h3";

export const routeExample = eventHandler(async (event) => {
	const body = await readBody(event);
	// => const body: any
});

Describe the bug

When using readBody, the output type is typed as Promise<any>. This in turn means it's very easy to accidentally lose type safety from the response body, as TypeScript will treat any use of the response as valid (where it's most likely not going to be). By returning Promise<unknown> instead, h3 can explicitly communicate that the return type should be handled with care, instead of treating every use of it as valid. You can find a super basic example of the type of any "trap" in this playground: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgEwQFQO4hgXhgCjAVwFsAuGAwgIwFMAnASiwD4yiYBqGAJgG4BYAKAGhIsCiAQBPAIJgJpOLKwwARAAsqAGw0Z0NDQmV9+w6DDGSAqmADWYEKjCl8Nuw6VrN2mLv2GBAxBR0HHNpWTojQLQQEPEJK1t7MAigA. Note how the unknown body use throws a helpful error in this mistaken usage example.

Additional context

You can workaround the problem by providing the explicit type you expect in the override:

interface BodySchema {
  action: 'comment';
  message: string;
}

await readBody<BodySchema>(event);

or manually set unknown if you can't rely on the input body:

await readBody<unknown>(event);

Logs

No response

@pi0
Copy link
Member

pi0 commented Jun 25, 2024

Fixed by #791 for h3 v2 (coming!)

@pi0 pi0 closed this as completed Jun 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants