I created a TypeScript function that enforces a rule where a function must accept either zero or two arguments, but not just one. In other words, if the first argument is passed in, the second parameter becomes required.
Here is how the function looks like:
function bar<T, P>(a?: undefined extends P ? never : T, b?: P) { }
bar('') // This will result in an error, which is the intended behavior.
Initially, I had the conditional type set up differently, but it didn't work as expected:
function bar<T, P>(a?: P extends undefined ? never : T, b?: P) { }
bar('') // Surprisingly, this was considered okay, even though it shouldn't be.
When the second argument (P
) is not provided, it defaults to undefined
, which does indeed extend undefined. So why doesn't P extends undefined
work in this case?