Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get string value or first element of array as string

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.:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any shortcut in JavaScript?

>Solution :

like this:

function x(p:string|string[]){
 return Array.isArray(p)?p[0]:p
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading