itsundefined
itsundefined

Reputation: 1450

Merging object inside an interface in typescript

I have the following in a typing file:

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

Now I want to change the interface so that anObject also includes data2. I want the final form to be

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

I already tried doing this and it failed:

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

Instead of the anObject having both data and data2, it only has data2. Is there anyway to keep original keys?

Upvotes: 3

Views: 1329

Answers (1)

jcalz
jcalz

Reputation: 330411

Hmm, how about something like this:

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

That is: rename the original A out of the way to _A during import. Then extend it and merge in the new data2 property with the original by intersecting it with the looked-up anObject property.

Or, if you don't mind A being a type alias and not an interface, there's the simpler:

extend.ts

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

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

... in which you still rename the original out of the way, but then simply intersect it with the new part. Either method gives you the type you want:

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

Does that help?

Upvotes: 6

Related Questions