Is it possible to make return type of function dependent on the argument type?
JavaScript
x
2
1
const exampleFunction<T> = (initial?: T, anotherArgs) => { Some logic }
2
In this example by default we can use T | undefined, but I need that return type of function always be T if initial data is defined and (T | undefined) if it is undefined
Advertisement
Answer
Is it possible to make return type of function dependent on the argument type?
This question in a general sense is typically answered by function overloads.
In this case you could do something like:
JavaScript
1
13
13
1
function exampleFunction<T>(initial: T): T // overload 1
2
function exampleFunction(initial?: undefined): undefined // overload 2
3
4
// Implementation
5
function exampleFunction<T>(initial?: T): T | undefined {
6
return initial
7
}
8
9
const a: { abc: number } = exampleFunction({ abc: 123 }) // use overload 1
10
11
const b: undefined = exampleFunction() // use overload 2
12
const c: undefined = exampleFunction(undefined) // use overload 2
13
However, reading your question more carefully…
always be T if initial data is defined and (T | undefined) if it is undefined
You can change the second overload to:
JavaScript
1
2
1
function exampleFunction<T>(initial?: undefined): T | undefined // overload 2
2
But that will require a manual type for T
since none can be inferred.
JavaScript
1
2
1
const b: { def: string } | undefined = exampleFunction<{ def: string }>() // use overload 2
2