Skip to content

Instantly share code, notes, and snippets.

@dcefram
Last active November 9, 2022 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcefram/40faf090000012e5949cd84c896187a7 to your computer and use it in GitHub Desktop.
Save dcefram/40faf090000012e5949cd84c896187a7 to your computer and use it in GitHub Desktop.
Generate Typescript types based on json data
function generateTypes(obj, name) {
const parsed = Object.keys(obj).reduce((str, key) => {
let type = Array.isArray(obj[key]) ? typeof obj[key][0] : typeof obj[key];
if (type === 'object') {
type = key.charAt(0).toUpperCase() + key.slice(1, key.length - 1);
}
type = type === 'undefined' ? 'any' : type;
type = isArray ? type + '[]' : type;
return `${str}\n\t${key}: ${type};`;
}, '');
return `type ${name} = {${parsed}\n}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment