Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Combining multiple interfaces into just one

I have few interfaces I want to combine into just only one interface: Member:

interface Person {
  name?: {
    firstName?: string;
    lastName?: string;
  };
  age: number;
  birthdate?: Date;  
}

interface User {
  username: string;
  email: string;
}

interface Player {
  room: number;
  group?: number;
}

My question is: how can I create a new interface: Member by combining the above interfaces, so I end up having the following:

interface Member {
  firstName: string;
  lastName: string;
  age: number;
  birthdate?: Date;  
  username: string;
  email: string;
  room: number;
  group?: number;
}

Please, notice that the structure has changed a bit. For example, fields inside: Person["name"] are now included directly on the root level on the new interface. Also, those fields are now mandatory (they were optional before).

Thanks!

like image 295
Viewsonic Avatar asked Jun 14 '26 16:06

Viewsonic


2 Answers

Make Person interface to a "flaten" interface, let's create new interface called PersonName, the new interface will be like:

interface PersonName {
  firstName?: string;
  lastName?: string;
}

then, Person interface will come to:

interface Person {
  name?: PersonName;
  age: number;
  birthdate?: Date;
}

Finally, Member interface has been defined with syntax like:

interface Member extends Player, User, Omit<Person, 'name'>, PersonName  {}

All of code: Playground

like image 116
hoangdv Avatar answered Jun 17 '26 05:06

hoangdv


Now firstName and lastName are mandatory

interface Member extends User, Player, Omit<Person, 'name'> {
  firstName: string;
  lastName: string;
}

firstName and lastName are mandatory

like image 29
nickbullock Avatar answered Jun 17 '26 04:06

nickbullock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!