Home > Software design >  options to extend an interface with one different value without having to re-write that object?
options to extend an interface with one different value without having to re-write that object?

Time:12-23

What is the best approach to make a similar interface that is different in only one value, then to duplicate code and rewrite the object again ? Could this be done without union type ?

// A1
export interface FirstType {
  id: string;
  parentId: string;
  type: 'a1';
  data : string[]
  dataA : string[]
  dataB : string[]
  dataC : string[]
  dataD : string[]
  dataE : string[]
}

// A2
export interface SecondType extends FirstType {
   type: 'a2';
}

CodePudding user response:

You can use the Omit<T, K> utility type to produce a named type suitable for interface extension:

export interface SecondType extends Omit<FirstType, "type"> {
    type: 'a2';
}

Playground link to code

CodePudding user response:

You might like this approach:

export interface SecondType {
  type: 'a2';
}

type SecondTypeUnion = FirstType | SecondType;
  • Related