InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

Params decorators do not respect types (inversify-express-utils)

Open tspoke opened this issue 6 years ago • 7 comments

When using inversify-express-utils, the decorator @queryParam does not handle types correctly. The type of the parameter is always string for primitives types.

@httpGet("/test")
public test(@queryParam("count") count: number, @request() req, @response() res) {
  console.log(typeof count); // print 'string'
  console.log(count === 1); // print false because count is a string not a int
  return count;
}

Expected Behavior

@queryParam should handle primitive types appropriately with a type-check + cast if needed.

Current Behavior

Primitive types are always a string.

Your Environment

    "inversify": "4.13.0"
    "inversify-express-utils": "6.0.0"

tspoke avatar Oct 17 '18 14:10 tspoke

@tspoke do you think that it should be limited to number and string?

dcavanagh avatar Oct 18 '18 20:10 dcavanagh

@dcavanagh All primitives should be a good start ? (boolean, string, number, integer, float)

Maybe it could be interesting to extends to array and enum...

tspoke avatar Oct 22 '18 19:10 tspoke

I think that problably can't be done without read the type decorator generated by typescript directly(not enabled by default), and typescript doesn't even generate design time type decorator for complex type like array anyway.

So, even we do it, it will only support primitives.

mmis1000 avatar Oct 25 '18 09:10 mmis1000

All URL parameters are strings because they're in a URL, so I think this is by design.

Jameskmonger avatar Nov 15 '18 15:11 Jameskmonger

@Jameskmonger Yes, of course. Even if it's by design, casting types into the wanted format should/could be a great feature for :

• Type check on request (throwing wrong type exceptions) • Value casting for usage without casting by hand

tspoke avatar Nov 16 '18 08:11 tspoke

This can introduce subtle bugs if the developer isn't aware of it.

Either the annotation should force a string type, or it should cast to the destination type. Having a string sitting around inside of what claims to be an int, or bool, or whatever... that's dangerous. It bypasses the type checker.

It's even worse because -most- of the time it will work, due to runtime type coercion (thanks JavaScript 😑). But it is not correct.

grapereader avatar Apr 12 '21 07:04 grapereader

4 years after and it is still the case. Do you think there is a possibility to fix this ?

@request() req: TypeRequest

is casting to the right type when accessing req.params.

descampsk avatar Apr 02 '22 12:04 descampsk