Skip to content

Instantly share code, notes, and snippets.

@copleykj
Created February 3, 2020 01:25
Show Gist options
  • Save copleykj/f1126b1ae1a71aa7a6b32f8ca3923081 to your computer and use it in GitHub Desktop.
Save copleykj/f1126b1ae1a71aa7a6b32f8ca3923081 to your computer and use it in GitHub Desktop.
Dirty way to output types for an object such as a Mongo documents
// This isn't comprehensive and is a pretty dirty hack piece of code,
// but it gets you close when you have a ton of fields in mongo
// collection documents that you need to create interfaces for
function makeTypes(obj: { [key: string]: any }, depth: number = 0) {
if (obj) {
let types: string = '';
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (value) {
if (Array.isArray(value)) {
const first = value[0];
if (typeof first === 'string' || typeof first === 'number' || typeof first === 'boolean') {
types += `${' '.repeat((depth + 1) * 2)}${key}: ${typeof first}[]\n`;
} else {
types += `${' '.repeat((depth + 1) * 2)}${key}: ${makeTypes(first, depth + 1)}[]\n`;
}
} else if (typeof value === 'object') {
let typeStr: string;
if (value instanceof Date) {
typeStr = 'Date';
} else {
typeStr = makeTypes(value, depth + 1);
}
types += `${' '.repeat((depth + 1) * 2)}${key}: ${typeStr}\n`;
} else {
types += `${' '.repeat((depth + 1) * 2)}${key}: ${typeof value}\n`;
}
}
});
return `{\n${types}${' '.repeat(depth * 2)}}`;
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment