Typescript 基于接口从另一个对象创建一个对象

Hie*_*enz 7 typescript

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

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

export interface ExampleInterface {
  property1: string;
  property2: string;
}
Run Code Online (Sandbox Code Playgroud)

进而

const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties;
Run Code Online (Sandbox Code Playgroud)

提前谢谢你。

Rod*_*igo 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;
 }
Run Code Online (Sandbox Code Playgroud)

使用该函数的示例:

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

const objB: ExampleInterface = createExampleInterface(objA);

console.log(objB);
Run Code Online (Sandbox Code Playgroud)

在https://stackblitz.com/edit/typescript-rjgcjp中尝试一下