Skip to content
Advertisement

How to make one type depends on argument

Is it possible to make return type of function dependent on the argument type?

JavaScript

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

Playground


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

But that will require a manual type for T since none can be inferred.

JavaScript

Playground

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement