打字稿基于接口从另一个对象创建一个对象

时间:2020-01-15 14:56:13

标签: typescript

我想从另一个对象创建一个ExampleInterface对象,但仅保留ExampleInterface包含的那些属性。

是否可以不手动复制每个密钥?

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

然后

const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties;

先谢谢你。

2 个答案:

答案 0 :(得分:0)

可能的解决方法是上述功能:

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

使用函数的示例:

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

const objB: ExampleInterface = createExampleInterface(objA);

console.log(objB);

https://stackblitz.com/edit/typescript-rjgcjp中试用

答案 1 :(得分:0)

因此,我认为一个类可能是一个更好的选择,因为您可以在其中创建一个构造函数,并将另一个对象作为参数提供给它,如下所示:

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

    }

让我知道是否有帮助:)