在打字稿中的界面内合并对象

Merging object inside an interface in typescript

我在输入文件中有以下内容:

interface A {
    anObject: {
        data: string;
    };
    someOtherData: boolean;
}

现在我想更改接口,使 anObject 也包含 data2。我希望最终形式是

interface A {
    anObject: {
        data: string;
        data2: string;
    };
    someOtherData: boolean;
}

我已经尝试这样做但失败了:

interface A {
    anObject: {
        data2: string;
    }
}

而不是 anObject 同时具有数据和数据 2,它只有数据 2。无论如何要保留原始密钥?

嗯,这样的怎么样:

orig.ts

export interface A {
    anObject: {
        data: string;
    };
    someOtherData: boolean;
}

extend.ts

import {A as _A} from './orig'

interface A extends _A {
  anObject: _A['anObject'] & {
    data2: string;
  }
}

即:在import. Then extend it and merge in the new data2 property with the original by intersecting it with the looked-up anObject 属性.

期间将原来的A重命名为_A

或者,如果您不介意 A 作为 type 别名而不是 interface,还有更简单的方法:

extend.ts

import {A as _A} from './playground'

type A = _A & {
  anObject: {
    data2: string;
  }
}

... 其中您仍然重命名原始部分,但随后只需将其与新部分相交即可。两种方法都可以为您提供所需的类型:

declare const a: A;
a.anObject.data.charAt(0); // okay
a.anObject.data2.charAt(0); // okay

有帮助吗?