Post(s) tagged Typescript Interface

Typescript Interface Pick, Omit usage, and Extends multiple interfaces

Sample interfaces

export interface Credentials {  
  email: string;
  password: string;
}

export interface User {
  firstName: string;
  lastName: string;
  age: number;
}

Pick constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type

Pick syntax

Pick<Type, Keys>

Example

var newInterface: Pick<Credentials, 'email'> = {} as Pick<Credentials, 'email'>;
//newInterface contains email only

Omit constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).

Omit syntax

Omit<Type, Keys>

Example

var newInterface: Pick<Credentials, 'email'> = {} as Pick<Credentials, 'email'>;
//newInterface omits email

Extends multiple interfaces

interface UserCredentials extends Credentials, User { }  //Extends Credentials, User
interface UserCredentials extends Credentials, Pick<User, 'firstName' | 'lastName' > { }  //Extends Credentials, User (firstName, lastName only)
interface UserCredentials extends Credentials, Omit<User, 'firstName' | 'lastName' > { }   //Extends Credentials, User (age only)


Posted on February 18, 2022
Sponsors