Iterate over interface properties in TypeScript

Viewed 100041

I need to map interface properties to objects:

interface Activity {
  id: string,
  title: string,
  body: string,
  json: Object
}

I currently do:

headers: Array<Object> = [
  { text: 'id', value: 'id' },
  { text: 'title', value: 'title' },
  { text: 'body', value: 'body' },
  { text: 'json', value: 'json' }
]

This gets very repetitive. What I would like is something like this:

headers: Array<Object> = Activity.keys.map(key => {
  return { text: key, value: key }
})
4 Answers

If you are okay with having it added during a compile time and you are using TypeScript >= 2.4.1, you can try the way proposed here.

Basically, you should add the ts-transformer-keys dependency, custom transformer, like a basic one and you'll be able to list the properties like this:

import { keys } from 'ts-transformer-keys';

interface Props {
    id: string;
    name: string;
    age: number;
}
const keysOfProps = keys<Props>();

console.log(keysOfProps); // ['id', 'name', 'age']

This approach might be a bit overkill, but i use it since i need JSON schemas anyway for validating the back end's response structure. Getting the keys from interfaces is just a nice side-effect of converting typescript interfaces into json schemas:

Using a typescript to json schema converter, one could get interfaces keys along with their types. The resulting json objects are large and verbose, so a parsing helper function could come in handy to recursively constructing simpler JS objects the way you want out of them. The good news is that a json schema always has the same structure, so it's easy to navigate.

Related