Dada una interfaz simple:
interface IPerson { firstName: string; lastName: string; age: number; city: string; favoriteNumber: number; isMarried: boolean; hasDriverLicense: boolean; }¿Cómo puedo generar matrices con nombres clave divididos por tipo? El resultado esperado sería así:
['firstName', 'lastName', 'city'] // string ['age', 'favoriteNumber'] // number ['isMarried', 'hasDriverLicense'] // booleanSi tiene una instancia de la interfaz y solo necesita usar los tipos disponibles en JS (por lo tanto, no las interfaces), es posible construir una estructura básica basada en los tipos de cada propiedad como esta:
const example = { firstName: 'a', lastName: 'b', age: 1, city: 'c', favoriteNumber: 2, isMarried: true, hasDriverLicense: false, } const arraysOfTypes = (obj) => { // We'll build an object with types as keys const result = {} // Go through each property on the instance of the interface for (const [key, value] of Object.entries(obj)) { // Combine the existing keys and the new key into an array and add it to the result object result[typeof value] = [...(result[typeof value] || []), key] } console.log(result) } arraysOfTypes(example) Esto podría expandirse con una verificación de tipos compleja dentro del ciclo for para detectar fechas/interfaces y luego pasar sus nombres a result[typeof value] en lugar de typeof value , sin embargo, eso es muy específico para su solución.