Recently, I came across a perplexing issue while responding to this specific inquiry. It pertains to a scenario where a generic function's parameter is optional and its type involves the use of generics. Consider the following function structure:
function process<T>(data?: T) {
}
When attempting to narrow down the variable data
within the function by explicitly checking if it is undefined, like so:
data !== undefined ? data : 0;
// ^? T & ({} | null)
The variable data
becomes narrowed to T & ({} | null)
. However, utilizing typeof
results in the expected narrowing to just
T</code. This behavior remains consistent even within conditional statements.</p>
<pre><code>typeof data !== "undefined" ? data : 0;
// ^? T
A simple reproduction example, containing all the mentioned aspects, can be found here:
function process<T>(data?: T) {
data !== undefined ? data : 0;
// ^?
if (data !== undefined) {
data
// ^?
}
typeof data !== "undefined" ? data : 0;
// ^?
if (typeof data !== "undefined") {
data
// ^?
}
}
This raises questions about why this behavior occurs. Are there underlying differences between the two conditions that I overlooked? Could this possibly be a bug? Any insights into this peculiar behavior would be greatly appreciated.