Special generic constraint in JSDoc where multiple types are possible but only one at a time

15 Views Asked by At

I am starting to use JSDoc a lot and have run into a little difficulty with generics using the @template property. As an example, I have a function that takes two arguments, they may either be strings or numbers, but they must both be the same type. So arg1 and arg2 may both be strings or they may both be numbers, but calling the function with arg1 = string and arg2 = number (or arg1 = number and arg2 = string) would be invalid.

Is it possible to document a function in such a way with JSDoc? If so how?

I have tried the following, but it does not enforce the restriction as I would expect from other languages that support generics:

/**
 * @template {string | number} T
 * @param {T} a
 * @param {T} b
 */
function putTogether(a, b) {
    return a + b
}

const result = putTogether("number of typing problems: ", 1) // This is valid code, but I don't want it to be

The expectation/hope is that if T for a is a string, then T for b will also be a string, or if T for a is a number, T for b will also be a number, but this is not the case.

0

There are 0 best solutions below