Kai021195
Kai021195

Reputation: 833

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

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 !!!

Upvotes: 0

Views: 55

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 55142

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

Upvotes: 1

Related Questions