How to pick properties from an interface

adamlacombe

Adam LaCombe

Posted on October 14, 2020

How to pick properties from an interface

You can use the built-in type Pick. Pick<MyInterface, "prop1" | "prop2"> is a built-in type which allows you to pick specific properties from an interface.

A great use-case would be verifying user credentials. You might have a User interface such as the following:

interface User {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  password: string;
}
Enter fullscreen mode Exit fullscreen mode

Instead of creating a new interface with the email and password properties from the User interface, lets Pick them!

// without Pick
async function verifyLoginCredentials(credentials: { email: string, password: string }) {
  // ... ...
}

// with Pick
async function verifyLoginCredentials(credentials: Pick<User, "email" | "password">) {
  const user = await getUserByEmail(credentials.email);

  if (!passwordMatches(credentials.password, user.password)) {
    throw new BadRequestError('incorrect password');
  }

  return user;
}

verifyLoginCredentials({ email: "example@example.com", password: "123" });
Enter fullscreen mode Exit fullscreen mode
đź’– đź’Ş đź™… đźš©
adamlacombe
Adam LaCombe

Posted on October 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related