8

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!

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

2

Now firstName and lastName are mandatory

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

firstName and lastName are mandatory

Comments

1

You can use union of types to create a Member type definition. It will not be an interface. That is it creates an alias to types rather than new type. Yet it clearly shows the origin of the type and its members

type Member = Person["name"] & Pick<Person, "age" | "birthdate">
  & User & Player

to define the interface you extend those types

type T1 = Required<Person> ["name"]
interface Member extends
  T1,
  Pick<Person, "age" | "birthdate">,
  User,
  Player { }

another version of the picture is to use exclude construct

type T1 = Required<Person> ["name"]
interface Member extends
  T1,
  Pick<Person, Exclude<keyof Person,"name">>,
  User,
  Player { }

This allow you to modify propertis of Person and changes will propagate to the Member interface.

To make first and last name mandatory, that is required you mention this

type T1 = Required<Required<Person> ["name"]>

1 Comment

how can I make: firstName and lastName mandatory? they were optional on the original interfaces

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.