2017-08-14 208 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))