typescript迭代接口属性 [英] typescript iterate interface properties

查看:110
本文介绍了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.

你可以做的是:

const Activity = {
    id: "",
    title: "",
    body: "",
    json: {}
}

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

操场上的代码

这篇关于typescript迭代接口属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆