Last active
October 22, 2024 06:29
-
-
Save ankitarora05/0c962035f533743e5c83e5cfac2ba04b to your computer and use it in GitHub Desktop.
JavaScript Program to Convert a Json Object to a Typescript Interface
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
/** | |
* Function to convert a JSON object to a TypeScript interface with nested interfaces. | |
* @param {Object} obj - The JSON object to convert. | |
* @param {string} interfaceName - The name of the TypeScript interface. | |
* @returns {string} - The TypeScript interface as a string. | |
*/ | |
function jsonToTypeScriptInterface(obj, interfaceName = 'RootObject') { | |
let result = `interface ${interfaceName} {\n`; | |
const nestedInterfaces = []; | |
function parseObject(object, currentInterfaceName, indentLevel = 1) { | |
const indent = ' '.repeat(indentLevel); | |
Object.keys(object).forEach(key => { | |
const value = object[key]; | |
const valueType = determineType(value); | |
if (valueType === 'object' && !Array.isArray(value)) { | |
const nestedInterfaceName = capitalizeFirstLetter(key); | |
result += `${indent}${key}: ${nestedInterfaceName};\n`; | |
// Recursively parse the nested object and create a new interface | |
nestedInterfaces.push(parseObject(value, nestedInterfaceName, indentLevel + 1)); | |
} else if (Array.isArray(value)) { | |
const arrayType = determineArrayType(value); | |
result += `${indent}${key}: ${arrayType}[];\n`; | |
} else { | |
result += `${indent}${key}: ${valueType};\n`; | |
} | |
}); | |
let interfaceStr = `interface ${currentInterfaceName} {\n${result}\n}\n`; | |
result = ''; // Clear the result for next object interface | |
return interfaceStr; | |
} | |
// Determine the type of a value | |
function determineType(value) { | |
if (value === null) return 'null'; | |
if (value === undefined) return 'undefined'; | |
if (Array.isArray(value)) return 'array'; | |
if (typeof value === 'string') return 'string'; | |
if (typeof value === 'number') return 'number'; | |
if (typeof value === 'boolean') return 'boolean'; | |
if (typeof value === 'function') return '() => void'; // Handle functions, returning `void` by default | |
if (typeof value === 'object') return 'object'; // This will be handled recursively | |
return 'any'; // If the type cannot be determined, fallback to `any` | |
} | |
// Determine the array's type by inspecting the elements | |
function determineArrayType(array) { | |
if (array.length === 0) return 'any'; | |
const firstElementType = determineType(array[0]); | |
// Handle arrays of objects | |
if (firstElementType === 'object') { | |
return `{ [key: string]: any }`; // Generalize for object arrays | |
} | |
return firstElementType; | |
} | |
// Capitalize the first letter of the nested interface name | |
function capitalizeFirstLetter(string) { | |
return string.charAt(0).toUpperCase() + string.slice(1); | |
} | |
// Start parsing the root object | |
nestedInterfaces.push(parseObject(obj, interfaceName)); | |
// Combine all interfaces | |
return nestedInterfaces.join('\n'); | |
} | |
// Example usage | |
const json = { | |
name: "John Doe", | |
age: 30, | |
isActive: true, | |
address: { | |
street: "123 Main St", | |
city: "Anytown", | |
zip: "12345" | |
}, | |
preferences: { | |
notifications: { | |
email: true, | |
sms: false | |
}, | |
locationPreferences: { | |
country: "USA", | |
city: "San Francisco" | |
} | |
}, | |
metadata: null, | |
id: undefined, | |
calculateAge: function() { | |
return 30; | |
} | |
}; | |
const tsInterface = jsonToTypeScriptInterface(json, 'User'); | |
console.log(tsInterface); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment