TypeScript: Create intersection types when interface members conflict.

Let’s use:

interface A = {
   data: number;
}
interface B = {
  data: string;
}
interface C extends A, B {}

This will throw an error as data has two separately defined types. I think that it would be really useful to allow C to become a union of the two interfaces either implicitly or to allow explicit unions of the conflicting types. The ultimate result being that:

interface C extends A, B {} = { data: number | string; }

Otherwise, a new interface would have to be created which would be a duplication of effort or the type would have to be overridden with any, which defeats the purpose of having strict types.

It’s just a thought, but since TypeScript allows multiple inheritance with interfaces and has union types, I thought that this could be a beneficial merging of the two ideas.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 19 (7 by maintainers)

Most upvoted comments

I just found a partial workaround for this issue: you need an additional “adapter” interface in the middle of the hierachy which redefines the conflicting member as any:

interface A { value: string; }
interface B { value: number; }
interface AB0 extends A, B { value: any; } // "adapter" interface
interface AB extends AB0 { value: string | number; } // here you can define the member with whatever type you like

// but AB is not compitable with A and B, a cast is needed
var a: A;
var ab: AB;
a = ab; // error
a = <A>ab; //ok