Búsqueda de sitios web

Typescript crear un objeto a partir de otro objeto, basado en una interfaz


Quiero crear un objeto ExampleInterface a partir de otro objeto, pero conservar solo aquellas propiedades que contiene ExampleInterface.

¿Es posible sin copiar cada clave manualmente?

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

y luego

const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties;

Gracias de antemano.

Respuesta #1

Una posible solución es la función de arriba:

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

Ejemplo usando la función:

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

const objB: ExampleInterface = createExampleInterface(objA);

console.log(objB);

Pruébalo en https://stackblitz.com/edit/typescript-rjgcjp

Respuesta #2

Creo que, por lo tanto, una clase podría ser una mejor opción, porque allí puedes crear un constructor y darle el otro objeto como parámetro así:

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

    }

Déjame saber si ayuda :)

Artículos relacionados