【问题标题】:Typescript create an object from another object, based on an interfaceTypescript 基于接口从另一个对象创建一个对象
【发布时间】:2020-05-02 08:54:40
【问题描述】:

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

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

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

然后

const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties;

提前谢谢你。

【问题讨论】:

标签: typescript


【解决方案1】:

一个可能的解决方案是上面的函数:

 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试试吧

【讨论】:

  • 虽然在我的情况下我选择了“类而不是接口并使用构造函数”解决方案,但我认为这个答案对我的问题来说是正确的。
【解决方案2】:

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

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

    }

如果有帮助请告诉我:)

【讨论】:

  • 是的,最后我承认类比接口更适合我的情况,谢谢。 :)
  • 很高兴它有帮助:)
猜你喜欢
  • 2020-08-23
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多