Home > database >  Optional and required properties in TS interfaces
Optional and required properties in TS interfaces

Time:10-17

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 ?

CodePudding user response:

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;
}
  • Related