write a function to that takes two arguments. If the 2 args are integers, return the sum, else return the concatenation of the 2 args (assume if a and b is not number its a string)

By admin | 8 months ago

interviewjobstypescriptjavascriptvacancykeralait

In TypeScript, you can create a function that checks the types of the two arguments and either adds them if they are both numbers or concatenates them if at least one of them is not a number. Here's how you can implement such a function:

function sumOrConcatenate(a: any, b: any): number | string { if (typeof a === 'number' && typeof b === 'number') { return a + b; } else { return a.toString() + b.toString(); } } // Test cases console.log(sumOrConcatenate(5, 3)); // Should return 8 console.log(sumOrConcatenate('5', 3)); // Should return '53' console.log(sumOrConcatenate('hello', 'world')); // Should return 'helloworld'

This function, `sumOrConcatenate, takes two parameters a` and `b` of type `any. It checks if both parameters are numbers using typeof. If they are, it returns their sum. If not, it converts both parameters to strings (if they aren't already) and then concatenates them. The function can return either a number` or a string, hence the return type is number | string.