我需要将接口属性映射到对象:
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 }
})
原文由 Chris 发布,翻译遵循 CC BY-SA 4.0 许可协议
这种方法可能有点矫枉过正,但我使用它是因为无论如何我都需要 JSON 模式来验证后端的响应结构。从接口获取密钥只是将 typescript 接口转换为 json 模式的一个很好的副作用:
使用 typescript 到 json 模式转换器,可以获得接口键及其类型。生成的 json 对象又大又冗长,因此解析辅助函数可以派上用场,以递归方式以您想要的方式构造更简单的 JS 对象。好消息是 json 模式始终具有相同的结构,因此很容易导航。