-
Notifications
You must be signed in to change notification settings - Fork 91
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
Cast configuration variable to the provided type #36
Comments
@matthiashermsen Thanks for the request. I feel this is something subjective to the use case. Typescript is still evolving and sometimes, some declarations will state you to use a string PORT value than a number. Also, the generics are meant for the purpose of declaration and not definition. At this stage, I'd say it'd be nice to have an option added to the .get("PORT", { castTo: "number" }) However, I'd leave the final decision on @kamilmysliwiec. Thanks again! |
Thanks to your reply :) I think you are right. But I was expecting something like this: config.get("PORT"); you obviously just get the value as a string. But when providing a "generic" type config.get<number>("PORT"); then you explicitly want to cast the value before returning it. But yeah, this is just a suggestion and my personal opinion :) |
This "generic" type is wiped out after the compilation. The following line of code: config.get<number>("PORT"); will be eventually transpiled to a vanilla JavaScript: config.get("PORT"); Hence, we can't inter what type you expect at runtime.
@prateekkathal you should use custom configuration files for this |
I'm submitting a...
Current behavior
When fetching configuration values via config service there is no type conversion although I pass in a desired type.
Expected behavior
I would expect the config service to cast the configuration value to the type that I passed in. If that fails, it throws an exception.
Minimal reproduction of the problem with instructions
Create a new application via NestJs CLI.
Install the config module
Create a .env file in the root directory with the content
Update the app.module.ts to
Update the main.ts file to
Start the application via
You should see the following console logs
What is the motivation / use case for changing the behavior?
So the config service usage is described in the docs
https://docs.nestjs.com/techniques/configuration#using-the-configservice
I read something about "type hinting". To me, this is a bit confusing / misleading. If I pass in the type I would expect a numeric cast.
You will still receive a string. I found the current code implementation here
https://github.com/nestjs/config/blob/master/lib/config.service.ts
To solve the current example I could do
but a cast would be awesome :)
Environment
The text was updated successfully, but these errors were encountered: