0

I would like to combine multiple interfaces that have properties with conflicting types, where the combined interface is a list of all potential keys with the widest possible type definition for each key.

Example:

interface Dog {
  type: "dog";
  name: string;
  owner: "Bob" | "Bobette";
}

interface Cat {
  type: "cat";
  name: number;
  owner: "Bob" | "Bobette" | "Jeff";
}

interface Giraffe {
  type: "giraffe";
  height: number;
}

type CombinedInterface<Dog, Cat, Giraffe> would equal {
  type: "dog" | "cat" | "giraffe";
  name?: string | number;
  owner?: "Bob" | "Bobette" | "Jeff";
  height?: number;
}

Where CombinedInterface could take any number of interfaces.

Thanks in advance for any help!

Edit for clarity:

CombinedInterface would be a generic, e.g. type CombinedInterface<I1, I2, ..., IN>, for which CombinedInterface<Dog, Cat, Giraffe> would return the type shown above.

  • Why is `CombinedInterface` a type and not an interface? And what is wrong with your solution? Could you clarify the question? – Paul May 13 '20 at 16:04
  • Sorry I wasn't clear - I mean that CombinedInterface would be a generic that can take any number of interfaces. i.e. something like type CombinedInterface = something, so one could then call it with any interfaces. CombinedInterface would return the type shown above. – Henry Davies May 13 '20 at 16:14
  • Does this answer your question? https://stackoverflow.com/questions/56296506/typescript-generic-interface-as-union-of-other-interfaces – Paul May 13 '20 at 16:22
  • It does indeed! Thanks very much. Should I flag this question as duplicate, or delete? – Henry Davies May 13 '20 at 16:28
  • Mark it as duplicate. :) – Paul May 13 '20 at 16:40

0 Answers0