Type 'string | undefined' is not assignable to type 'TReq extends true ? string : string | undefined'.
Type 'undefined' is not assignable to type 'TReq extends true ? string : string | undefined'.(2322)
Now, I honestly wish I could provide some solid type theory here and explain why the TypeScript type checker
cannot infer that the that the returned value can be undefined, but I'm not sure why.
If you know, please reach out and let me know!
##The solution
TypeScript supports declaring overloads which allows you to define the signature for a function which can accept different types of parameters.
JavaScript itself not supporting overloads per-se, but rather runtime type checking is used to check the argument types (or length in case of variadic parameters using the arguments keyword).
Note
This is a similar concept to monomorphization in other languages, where generic functions get compiled to a different implementation depending on the type. In vast constrast, however, in this case the implementation stays the same, but the returned type is different according to the generic type parameter.
Using overloading, this becomes simple - we simply define the signature for each type instantiation that the function can accept:
As you can see, there are now two overloads, for each possible value of the required parameter.
The undefined case even works, which is useful for having the default case be that the environment variable is required.