I want my function to be typed in 2 scenarios depending on how the user uses the function. If the user uses just a number they type of param
will be number
. if they use an object for options it will be of type { num: number; dp: number }
. This I have working but I want it to be typed for intellisense so when the user hovers they can see type num
represents the input number and type dp
represents the number of digits to round to but if they just type a number as param
then that to be typed as 'a number to round to the nearest int' This is the code I have but cannot get it to do exactly what I want. Any help would be appreciated! Thank you.
/**
* Returns a rounded numbers. If dp isn't entered the number returned will be rounded to the nearest integer.
* @param param - The rounding options or a number to round to an int.
* @param dp - The decimal places to round to.
* @param num - The number to round.
* @returns An rounded number.
*/
const round = (param: { num: number; dp: number } | number) => {
if (typeof param === 'number') return Math.round(param);
const { dp, num } = param;
return Math.round(num * Math.pow(10, dp)) / Math.pow(10, dp);
};
Simply the problem is how to detect both scenarios in TS/JSDoc and type for it