DEV Community

Cover image for How to pick properties from an interface
Adam LaCombe
Adam LaCombe

Posted on • Originally published at adamlacombe.com on

3 1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more