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

Allow users to control type coercion for route schema #1145

Open
el-tumakov opened this issue Mar 28, 2025 · 1 comment
Open

Allow users to control type coercion for route schema #1145

el-tumakov opened this issue Mar 28, 2025 · 1 comment
Labels
enhancement New feature or request

Comments

@el-tumakov
Copy link

What is the problem this feature would solve?

Currently, Elysia automatically coerces t.Number() and t.Boolean() to t.Numeric() and t.BooleanString() when used in route schemas for parameters, headers, and queries. While this behavior is useful in many cases, it is not configurable. There may be scenarios where users want to explicitly disable this coercion for more strict type validation.

What is the feature you are proposing to solve the problem?

Introduce a configuration option that allows users to enable or disable automatic type coercion for route schemas. This could be implemented via a framework-level setting (e.g., config.coerce) or per-route configuration.

For example:

new Elysia({ coerce: false })
    .get('/:id', ({ id }) => id, {
        params: t.Object({
            id: t.Number() // Should not be coerced to t.Numeric()
        })
    });

Alternatively, a per-route override could be implemented:

new Elysia()
    .get('/:id', ({ id }) => id, {
        params: t.Object({
            id: t.Number()
        }),
        options: { coerce: false }
    });

What alternatives have you considered?

  • Manually validating and parsing values within route handlers, which adds extra boilerplate code and defeats the purpose of using schemas.
  • Extending t.Number() with a custom validation schema, which is less intuitive and requires additional work.

Adding configurability would provide more flexibility while maintaining Elysia’s ease of use.

@el-tumakov el-tumakov added the enhancement New feature or request label Mar 28, 2025
@ledihildawan
Copy link

This idea is good, but it seems like it's not something commonly found in other frameworks. Besides, URLs are inherently in string format, so it's better to validate them manually according to our needs.

.get('/:id', ({ params: { id } }) => id, {
    params: t.Object({
      //   id: t.RegExp(/^\d+$/),
      id: t.String({ format: 'regex', pattern: '^\\d+$' }),
    }),
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants