1

I have data that can have one set of identifying fields, a second set, or both. I have that coded in interfaces like this.

export interface IRecordIdBase {
    RecordType: enumRecordType;
}

export interface IRecordIdA extends IRecordIdBase {
    AlphaCode: string;
    LocationCode: string;
}

export interface IRecordIdB extends IRecordIdBase {
    BravoCode: string;
    LocationCode?: string;
}

The trouble is that the only way I know to make a "this, that, or both" item is with a union type.

export type IRecordId = IRecordIdA | IRecordIdB | (IRecordIdA & IRecordIdB);

However, I can't later extend a type. I use different subsets of data, requiring different interfaces, but all have the same ID structure. For example,

// can't extend IRecordId
export interface IRecordContent extends IRecordId {
    RecordData: string;
    RecordAuthor: string;
}

export interface IRecordMeta extends IRecordId {
    RecordAdded: string;
    RecordLastUpdated: string;
}

Is there an interface pattern or other solution that addresses this? I'm using TypeScript v2.6.1.

nshew13
  • 3,052
  • 5
  • 25
  • 39
  • 1
    [You can create a type from IRecordID with additional properties using intersection type](https://stackoverflow.com/questions/41385059/possible-to-extend-types-in-typescript/41385149#41385149). – artem Nov 15 '17 at 18:10
  • You can't use a union type because you're not giving the compiler anything definitive to extend; it doesn't know which properties should be included in the new interface. Would creating an interface, `IRecordIdAB`, that extends both `IRecordIdA` and `IRecordIdB` help? That way you can extend `A`, `B`, or `AB`. – adrice727 Nov 15 '17 at 18:54
  • Thanks, adrice. So, in your example, would I have `export interface IRecordContent extends IRecordIdAB` or `export interface IRecordContent extends IRecordIdA, IRecordIdB, IRecordIdAB`? Doesn't that mean it has to have all the properties of both A and B? – nshew13 Nov 16 '17 at 17:43

0 Answers0