Created
September 8, 2021 18:44
-
-
Save zjkuang/6ebed6217912f4d6c3551e663d6dc103 to your computer and use it in GitHub Desktop.
TypeScript: Convert any to string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function anyToString(a: any): string { | |
if (Array.isArray(a)) { | |
let s = '['; | |
const arr = a as Array<any>; | |
const numberOfElements = arr.length; | |
arr.map((e, index) => { | |
let eString = anyToString(e); | |
s = s + eString; | |
if (index + 1 < numberOfElements) { | |
s = s + ','; | |
} | |
}); | |
s = s + ']'; | |
return s; | |
} else if (typeof a === 'object') { | |
let s = '{'; | |
const o = a as object; | |
const entries = Object.entries(o); | |
const numberOfEntries = entries.length; | |
entries.map(([k, v], index) => { | |
let vString = anyToString(v); | |
s = s + `"${k}":${vString}`; | |
if (index + 1 < numberOfEntries) { | |
s = s + ','; | |
} | |
}); | |
s = s + '}'; | |
return s; | |
} else { | |
switch (typeof a) { | |
case 'function': | |
return '[function]'; | |
case 'symbol': | |
return '[symbol]'; | |
case 'string': | |
return `"${a}"`; | |
} | |
} | |
return `${a}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment