0

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",
};
Md. Fazlul Hoque
  • 15,806
  • 5
  • 12
  • 32
mksawic
  • 1
  • 1
  • 1

2 Answers2

2

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
}
spirift
  • 2,994
  • 1
  • 13
  • 18
1

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

Pilpo
  • 1,236
  • 1
  • 7
  • 18
  • This got me going to where I needed to go as a single dto row lookup and api value mapper. Thanks a bunch. – pythlang Aug 16 '22 at 03:08