Home > Enterprise >  How to combine two interface with a type which has different attribute type in Typescript
How to combine two interface with a type which has different attribute type in Typescript

Time:01-15

I tried to combine two interface with a type like the following, I tried to do that with the intersection of Admin & User, not just re-define the type again, is there a way to do this ?

// Define type PowerUser which should have all fields
// from both User and Admin (except for type),
// and also have type 'powerUser' "without" duplicating
// all the fields in the code.
/*
const example: PowerUser = {
  type: "powerUser",
  age: 20,
  name: max,
  occupation: "FE",
  role: "ma"
}

*/

interface User {
  type: "user";
  name: string;
  age: number;
  occupation: string;
}

interface Admin {
  type: "admin";
  name: string;
  age: number;
  role: string;
}

type PowerUser = (User | Admin) & { type: "poweruser"}; // not working !!!

CodePudding user response:

Use Omit !

interface User {
  type: "user";
  name: string;
  age: number;
  occupation: string;
}

interface Admin {
  type: "admin";
  name: string;
  age: number;
  role: string;
}

type PowerUser = Omit<User, 'type'> & Omit<Admin, 'type'> & { type: "powerUser"};

Playground

  • Related