Search code examples
angulartypescriptmergedeclaration

TypeScript declaration merging of interfaces in different files in an Angular project


Which way can I implement declaration merging when the interfaces are in separated files?

There is an interface in file all-data.interface.ts

export interface IAllData {
 data1: string;
 data2: string;
}

There are another interfaces like as

data-one.interface.ts

export interface IAllData {
 data2: number;
 data3: number;
}

and

data-two.interface.ts

export interface IAllData {
 data4: boolean;
 data5: boolean;
}

the class: all-data.model.ts

export AllData implements IAllData {
 data1: string;
 data2: string;
 data2: number;
 data3: number;
 data4: boolean;
 data5: boolean;
}


public applyData(data: IAllData) {
 console.log(data.data4);
}

When I passing as parameter the IAllData based instance to a function, inside the function when I try to use the the properties of instantiated class

Property 'data4' does not exist on type 'IAllData'.

As I tried doesn't matter I wrap all declarations into the same namespace.

Could you please explain to me, What I missed?


Solution

  • You will have to import the interfaces and give them aliases, since the have the same name:

    import { IAllData as IAllDataOne } from 'src/path/to/data-one.interface';
    import { IAllData as IAllDataTwo } from 'src/path/to/data-two.interface';
    
    export class AllData implements IAllDataOne, IAllDataTwo  {
     data1: string;
     data2: any;
     data3: number;
     data4: boolean;
     data5: boolean;
    }
    
    
    public applyData(data: AllData) {
     console.log(data.data4);
    }
    

    Alternatively, you can create a new interface that extends your others:

    import { IAllData as IAllDataOne } from 'src/path/to/data-one.interface';
    import { IAllData as IAllDataTwo } from 'src/path/to/data-two.interface';
    
    export interface IAllDataExtended extends IAllDataOne, IAllDataTwo {
      newData: any;
    }
    
    export class AllData implements IAllDataExtended  { // I don't know type of AllData based on info provided
     data1: string;
     data2: any;
     data3: number;
     data4: boolean;
     data5: boolean;
     newData: any;
    }
    
    
    public applyData(data: IAllDataExtended) {
     console.log(data.data4);
    }