Given a simple interface:
interface IPerson {
firstName: string;
lastName: string;
age: number;
city: string;
favoriteNumber: number;
isMarried: boolean;
hasDriverLicense: boolean;
}
How can I generate arrays with key names divided by type? The expected result would be like this:
['firstName', 'lastName', 'city'] // string
['age', 'favoriteNumber'] // number
['isMarried', 'hasDriverLicense'] // boolean
CodePudding user response:
If you have an instance of the interface, and you only need to use types available in JS (so, not interfaces), it is possible to build a basic structure based on the types of each property like this:
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)
This could be expanded with complex type checking inside the for loop to detect dates/interfaces and then pass their names into result[typeof value]
in place of typeof value
, however that is very specific to your solution.