Home > OS >  Create an object from interface with keys and values - typescript
Create an object from interface with keys and values - typescript

Time:10-08

Is there any way to create an object based on an interface which use the same keys and values?

For example. I have following interface:

interface Person {
  name: string;
  age: number;
}

and I would like to generate an object which looks like this:

const personFieldNames = {
  name: "name",
  age: "age",
};

CodePudding user response:

You can't make an object from an interface because the types only exist at compile time but, you can make a type from an object using typeof.

const person = {
  name: 'name',
  age: 0
}

type Person = typeof person

const john: Person = {
  name: 'john',
  age: 20
}

CodePudding user response:

You can't loop through properties of Interface because they are only for compile time. But what you can do, is creating an object from your Interface and loop over its properties.

interface Person {
  name: string;
  age: number;
}

const personFieldNames: Person = {
  name: "name",
  age: 123,
};

let newObject = {};

Object.keys(personFieldNames)
.forEach(key => {
    newObject = {... newObject, [key] : key};
})

console.log(newObject);

Output:

[LOG]: {
  "name": "name",
  "age": "age"
} 

Or you can use the ts-transformer-key from here

  • Related