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

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay