7

I want to create an ExampleInterface object from another object, but keep only those properties that ExampleInterface contains.

Is it possible without copying each key manually?

export interface ExampleInterface {
  property1: string;
  property2: string;
}

and then

const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties;

Thank u in advance.

2

2 Answers 2

1

A possible solution is the function above:

 function createExampleInterface(sourceObject: ExampleInterface): ExampleInterface 
 {
      const emptyExampleInterface: ExampleInterface = {
        property1: '',
        property2: ''
      };
      const interfaceProperties = Object.keys(emptyExampleInterface);
      const targetObject: ExampleInterface = Object.assign({}, sourceObject) ;

      for (let property of Object.keys(targetObject)) {    
        if (interfaceProperties.indexOf(property) < 0) {      
          delete targetObject[property];
        }
      }
      return targetObject;
 }

Example using the function:

const objA = {
  property1: 'Property 1',
  property2: 'Property 2',
  property3: 'Property 3'
}

const objB: ExampleInterface = createExampleInterface(objA);

console.log(objB);

Try it in https://stackblitz.com/edit/typescript-rjgcjp

Sign up to request clarification or add additional context in comments.

1 Comment

Although in my case I chose the 'class instead of interface and use constructor' solution, imo this answer is the correct one for my question.
1

I think therefore a class might be a better choice, because there you can create a constructor and give it the other object as parameter like this:

    export class ExampleDomainObject {
        constructor(obj: AnotherObjectThatHasMoreProperties) {
            this.myProp = obj.myProp;
            // here you apply all properties you need from AnotherObjectThatHasMoreProperties
        }

    }

Let me know if it helps :)

3 Comments

Yes, finally I admitted that classes would fit more to my case than interface, thanks. :)
Glad it helped :)
Don't you still have to explicitly copy all the properties of the other object, which is what this question seeks to avoid?

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.