Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over interface properties in TypeScript

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 } }) 
like image 239
Chris Avatar asked Aug 14 '17 08:08

Chris


Video Answer


1 Answers

You can't, interfaces are only for compile time because javascript doesn't support it.

What you can do is something like:

const Activity = {     id: "",     title: "",     body: "",     json: {} }  type Activity = typeof Activity; const headers: Array<Object> = Object.keys(Activity).map(key => {     return { text: key, value: key } }); 

(code in playground)

like image 160
Nitzan Tomer Avatar answered Sep 18 '22 19:09

Nitzan Tomer