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)

Byadmin
2 years 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.

A

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.

Find Roommates
Connect with potential roommates for your new city
Rent Flats
Find affordable accommodation near your workplace
Sell Old Books
Turn your study materials into extra income
Sell Vehicles
Sell your old vehicle or find a new one
Explore Life Solutions

Also explore Bharath Surplus for buying, selling, and auction opportunities