I have a function which takes in two parameters, something like:
function example(type, val) {
// handle "val" based on "type"
}
The acceptable types for val
depend on type
. The type
parameter will always be one of a few select strings. For example, my JSDoc may look something like the following:
/**
* Handles the value of "val" based on the "type" parameter.
* @function example
* @param {"number" | "string" | "boolean"} type - The type of the "val" parameter.
* @param { ????? } val - The value to handle.
* @returns {void}
*/
function example(type, val) {
// handle "val" based on "type"
}
It’s worth noting that "number"
, "string"
, and "boolean"
aren’t actually the allowed values of type
in my real code; I’m only using them here for demonstration as it makes the problem easier to understand.
As seen in the above code, type
can take on a few select values. If type="number"
, for example, then val
should only be allowed to be a number.
I thought I could union a few typedefs together to achieve the result I’m looking for, but I wasn’t entirely sure how this would even work as I’m dealing with functions, not objects.
Any suggestions would be appreciated!
2
Answers
Just discovered the
@overload
tag, which seems to do what I need:Not entirely sure why this isn't documented on the JSDoc website, but it seems to work with IntelliSense on VS Code.
Ok. I think now, after some comments I get what you want.
Also, there’re more two (+1) examples that could be helpful.
1st case is that you want to produce IntelliSense error if the
value
is not of the same type as the given in thetype
parameter. I recommend directly using classes here.2nd case is that you want to parse your value differently depending on what
type
is. Note that in this case (example2
) I’ve kept thetype
parameter type asstring
.3rd case is a suggestion based on the comments.
NOTE: You can actually mix those two approaches.