Note: I'm doing this in the context of NestJS, and welcome any answers that leverage it, but this is a more general question about ParameterDecorators, as nest is just building a ParameterDecorator type.
Let's say I have a ParameterDecorator @ParseIt that I invoke as such
function func(@ParseIt() arg: CustomType) { ... }
so @ParseIt takes whatever the original arg is and parses it into a CustomType. I have this workign without issue. What I can't seem to support is the following
function func(@ParseIt() arg: CustomType) { ... }
function func2(@ParseIt() arg?: CustomType) { ... }
where ParseIt works like you'd expect. I can get it to either work where it always functions as string | undefined -> CustomType | undefined, or string -> CustomType, but not where it depends on the optionality of the argument it is modifying
Is this possible in typescript? I figure it probably is possible with typescript 5's powerful decorators, but I don't know them well enough to say. I thought about making ParseIt just always go from string | undefined -> CustomType | undefined, so in the case of
function func(@ParseIt() arg: CustomType) { ... }
the type signature would "protect" us from the fact that underneath the covers, the parse could support undefined...but I'm worried that this could open us up to potential errors (this is where NestJS comes into play, because when you're defining a route and its methods, the ultimate invocation over the network isn't typed, that is to say, if they don't pass in arg, even if you required it, it will invoke the method, and it'd be up to ParseIt to fail out). Ideally I want the ParseIt function to error out in this case, but not in the case of arg?. Not sure if that is possible without two separate decorators, though