Jason Leavers
Jason Leavers

Reputation: 5

Optional and required properties in TS interfaces

here I have simple example typescript interfaces:

interface A: {
   id: number;
   email: string;
}

interface B extends A {
   login: string;
   password: string;
}

What I want: IF I create an object from interface A all properties are required. If I create B - the 'email' property from A is optional, all other properties (B) are required. Is it possible ?

Upvotes: 0

Views: 526

Answers (1)

Svetoslav Petkov
Svetoslav Petkov

Reputation: 1575

Here is the solution. You need to pick the email property from A:

Pick<A,"email">

and make it optional with the PArtial

interface B extends Partial<Pick<A,"email">>

Full code and playgorung

interface A {
   id: number;
   email: string;
}

interface B extends Partial<Pick<A,"email">> {
   login: string;
   password: string;
}

Upvotes: 2

Related Questions