Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
How to split an interface into multiple arrays of keys separated by type?

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
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!