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

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This got me going to where I needed to go as a single dto row lookup and api value mapper. Thanks a bunch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.