Closed as not planned
Description
🔎 Search Terms
"optional" "arguments" "inference" "generic" "narrowing" "parameters"
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about optional parameters
(tested on latest minor version of v3, v4, and v5)
⏯ Playground Link
💻 Code
// Broken example with conditional types
function myFunction(x?: number): typeof x extends undefined ? string : number {
if (x === undefined) {
const z = x // It knows typeof x === undefined here, but still wants to return a number
// Code for when x is not supplied
return "Type A";
} else {
// Code for when x is supplied
return x * 2; // Example, you can return a different type here
}
}
const result1: string = myFunction(); // I'd expect this one to be typed as a string
const result2: number = myFunction(5); // This one types correctly
// Partially working example
const partiallyWorking = (defaultValue?: number) => {
if (defaultValue === undefined) {
return "nothing"
} else {
return defaultValue
}
}
// Here both are typed as number | string, which is at least correct, but not as strong as it could be
const ex1 = partiallyWorking(1)
const ex2 = partiallyWorking()
// Broken example
class P<Z> {
constructor (z: Z) {
console.log(z)
}
}
type T = { a: 1}
const optional = <X = T>(defaultValue?: X) => {
if (defaultValue === undefined) {
return new P<T | undefined>(undefined)
} else {
return new P<T | X>(defaultValue)
}
}
// Both of these are typed as P<T | undefined>.
// Ideally, the first one should be typed as
// P<T | number> and the second one typed as
// P<T | undefined>. Also acceptable would be
// both being typed as P<T | X> | P<T | undefined>
const t1 = optional(14)
const t2 = optional()
🙁 Actual behavior
Specifically in the third case, the return type was incorrectly narrowed to the wrong value.
🙂 Expected behavior
The function's return type should either be the union of the two possible return cases, or it should be narrowed based on the value of the optional argument.
Additional information about the issue
No response