Hienz
Hienz

Reputation: 718

Typescript create an object from another object, based on an interface

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.

Upvotes: 7

Views: 10652

Answers (2)

Rodrigo
Rodrigo

Reputation: 2503

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

Upvotes: 1

dave0688
dave0688

Reputation: 5770

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 :)

Upvotes: 1

Related Questions