Skip to content

Instantly share code, notes, and snippets.

@GuilhermeRossato
Created July 17, 2021 18:14
Show Gist options
  • Save GuilhermeRossato/feb17ab682ebb545ad99a6e01bf34218 to your computer and use it in GitHub Desktop.
Save GuilhermeRossato/feb17ab682ebb545ad99a6e01bf34218 to your computer and use it in GitHub Desktop.
JS function to generate JSDoc type hint from an object instance
export function generateJSDocsFromObj(obj) {
if (typeof obj !== "object") {
return typeof obj;
}
if (obj instanceof Array) {
if (obj.length <= 0) {
return "any[]";
} else {
return generateJSDocsFromObj(obj[0]);
}
}
let result = {};
for (key in obj) {
result[key] = generateJSDocsFromObj(obj[key]);
}
return JSON.stringify(result).replace(/\"/g, "").replace(/\,/g, ";");
}
import { generateJSDocsFromObj } from "./generateJSDocsFromObj.js";
/** @type {{a:number;b:{c:{d:string}}}} */
const object = {
a: 1,
b: {
c: {
d: "hello world"
}
}
};
console.log(generateJSDocsFromObj(object)); // {a:number;b:{c:{d:string}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment