遍历TypeScript中的接口属性 [英] Iterate over interface properties in TypeScript
本文介绍了遍历TypeScript中的接口属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将接口属性映射到对象:
I need to map interface properties to objects:
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' }
]
这变得非常重复.我想要的是这样的:
This gets very repetitive. What I would like is something like this:
headers: Array<Object> = Activity.keys.map(key => {
return { text: key, value: key }
})
推荐答案
您不能,接口仅用于编译时,因为javascript不支持它.
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 }
});
( 查看全文