skip to Main Content

Have the following function:

function x(p: string | string[]): string | string[];

How do I ensure that the following just outputs a single string value?

console.log(x());

I.e.:

console.log(x("Hello")); // should be "Hello"
console.log(x(["Hello", "World"])); // should be "Hello"

Any shortcut in JavaScript?

2

Answers


  1. like this:

    function x(p:string|string[]){
     return Array.isArray(p)?p[0]:p
    }
    
    
    Login or Signup to reply.
  2. You can use the fact that concat promotes scalars to arrays, and leaves arrays as is:

    function x(a) {
        return [].concat(a)[0]
    }
    
    console.log(x("Hello")); // should be "Hello"
    console.log(x(["Hello", "World"])); // should be "Hello"

    That is, if you’re actually looking for a "shortcut", and not a technically correct solution, which would be not having such a function in the first place.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search