Is there a way in TypeScript to create a function that can automatically determine what action to take based on the type of input it receives?
For instance, let's consider a function that calculates the maximum value.
In scenario A, if the input is a numeric array (i.e.,
type: number[]
), I want the function to return the max value. This can be achieved with:const calcMaxArr = (arr: number[]): number => { return Math.max(...arr) }
In scenario B, if the input data is an object and I want to find the key corresponding to the largest value, the function should do this:
const calcMaxObj = (obj: Record<string, number>): string => { return Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b); }
Although calcMaxArr()
and calcMaxObj()
work well individually, I am interested in combining them into one single function called calcMax()
. The challenge is for calcMax()
to intelligently decide whether to use calcMaxArr()
or calcMaxObj()
based on the input type.
If type: number[] -> calcMaxArr()
If type: Record<string, number> -> calcMaxObj()
Does TypeScript offer a feature that supports this kind of functionality?
EDIT
A tweet showcasing a similar concept in Python was brought to my attention. It might serve as a helpful analogy for those familiar with Python.
EDIT 2
I recently discovered that what I'm describing is essentially a generic function. Common Lisp, for example, offers built-in support for defining generic functions and methods.