如何在2个接口之间复制相似之处

时间:2019-06-03 02:20:21

标签: typescript

我具有以下结构:https://stackblitz.com/edit/angular-u8c9us

  export interface baseStruct {
    code: number;
    message: string;
}

export interface struct1 extends baseStruct {
    struct1: string
}

export interface struct2 extends baseStruct {
    struct2: string
}

我创建了一个sturcture1对象,我想创建一个structure2对象,该对象复制来自baseStruct的structure1元素,但删除其余部分。

我该如何实现?

    let newStruct1: struct1 = {
      code: 1,
      message: "hey",
      struct1 : "toto3"
    }

  let newStruct2: struct2 = {
      ...newStruct1,
      struct2: "ho"
  }

  console.log(newStruct2)

我希望newStruct2返回

{
 code :1
 message: "hey"
 struct2: "ho"
}

2 个答案:

答案 0 :(得分:0)

根据正在运行的Typescript版本,您可以删除某些强制类型转换,在3.5值中,索引签名将在3.5之前,而不会。

function omit<T extends object, K extends Array<keyof T>>(value: T, ...keys: K): Omit<T, K[number]> {
    return Object.keys(value)
        .filter((key) => !keys.includes(key as keyof T))
        .reduce<Omit<T, K[number]>>(
            (obj, key) => {
                return { ...obj, [key]: (value as any)[key] };
            },
            {} as any,
        );
}


let newStruct1: struct1 = {
    code: 1,
    message: "hey",
    struct1 : "toto3"
}
let newStruct2: struct2 = {
    ...omit(newStruct1, "struct1"),
    struct2: "ho"
}

console.log(newStruct2)

答案 1 :(得分:0)

您可以使用类似复制构造函数的方法来实现更多面向对象的方式。下面的代码应该可以工作。

export abstract class baseStruct {
    code: number;
    message: string;
    constructor(other?: baseStruct) {
        if (other) {
            this.code = other.code;
            this.message = other.message;
        }
    }
}

export class SimpleStruct extends baseStruct { };

export class struct1 extends baseStruct {
    struct1: string
}

export class struct2 extends baseStruct {
    struct2: string
    constructor(other?:struct1) {
        super(other);
    }
}

const b: struct1 = {
    code: 1,
    message: 'Message',
    struct1: 'Struct1'
}

console.log(new struct2(b));

输出:

struct2 { code: 1, message: 'Message' }