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)
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.
Written by admin
Career insights & tech expertise
Life Beyond the Job Search
While you're building your career, don't forget about the practical aspects of life. Whether you're relocating for a new job or just need to declutter, Bharath Surplus can help you with all your life needs.
Also explore Bharath Surplus for buying, selling, and auction opportunities