Typescript change interface properties

I need to map interface properties to objects:

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

I'm doing now:

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

It becomes very repetitive. I would like it to be like this:

   headers: Array<Object> = Activity.keys.map(key => {
       return { text: key, value: key }
   })
+4
source share
2 answers

You cannot, interfaces are for compile time only because javascript does not 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 }
});

( code on the playground )

+2
source

if you want to retain the ability of the interface, you can do the following: @Nitzan Tomer is right. Interfaces are part of the type system, so they are applicable only at compile time, since they are not specified in the transmitted code.

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))
0

Source: https://habr.com/ru/post/1683655/


All Articles