2017-08-14 78 views
3

我需要的接口属性映射到对象:打字稿迭代接口属性

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

我目前做的:

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

这会非常反复。我想要的是这样的:

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

回答

1

你不能,接口只用于编译时间,因为JavaScript不支持它。

你可以做的是一样的东西:

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

0

,如果你想保持你可以做以下的接口能力,@Nitzan Tomer的是对的。接口是类型系统的一部分,因此它们仅在编译时相关,因为它们在传输代码中被省略。

class Activity { 
    public id: string = ''; 
    public title: string = ''; 
    public body: string = '' ; 
    public json: Object = {}; 
} 

let activity = new Activity() 

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

console.log(JSON.stringify(headers))