tommybernaciak
tommybernaciak

Reputation: 390

Object that may contain objects of given interfaces

imagine you have three types of objects, for example:

interface A {
  testA: someDifferentType;
}

interface B {
  testB: someOtherType[];
}

interface C {
  testC1: string;
  testC2: number;
}

Now I have a root object that is an object that may include those 3 interfaces (but none is required) So for example this is a valid object:

{
  root: {
    testB: [{...}],
    testC1: 'test',
    testC2: 123
  }
}

What kind of type or interface it should be?

Upvotes: 0

Views: 23

Answers (1)

Terry
Terry

Reputation: 66228

Then you just need to define the object such that it is a union of the partial interfaces:

interface MyObj {
  root: Partial<A> & Partial<B> & Partial<C>
}

const myObj: MyObj = {
  root: {
    testB: [{...}],
    testC1: 'test',
    testC2: 123
  }
};

You can also combine them in a single partial type, i.e.:

interface MyObj {
  root: Partial<A & B & C>
}

Upvotes: 1

Related Questions