mksawic
mksawic

Reputation: 1

Create an object from interface with keys and values - typescript

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",
};

Upvotes: 0

Views: 6240

Answers (2)

spirift
spirift

Reputation: 3072

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
}

Upvotes: 2

Pilpo
Pilpo

Reputation: 1276

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

Upvotes: 1

Related Questions