Skip to content

Instantly share code, notes, and snippets.

@zjkuang
Created September 8, 2021 18:44
Show Gist options
  • Save zjkuang/6ebed6217912f4d6c3551e663d6dc103 to your computer and use it in GitHub Desktop.
Save zjkuang/6ebed6217912f4d6c3551e663d6dc103 to your computer and use it in GitHub Desktop.
TypeScript: Convert any to string
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