Created
July 17, 2021 18:14
-
-
Save GuilhermeRossato/feb17ab682ebb545ad99a6e01bf34218 to your computer and use it in GitHub Desktop.
JS function to generate JSDoc type hint from an object instance
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
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, ";"); | |
} |
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
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