How TypeScript's Pick utility type protects sensitive data

The scariest bug in production? Accidentally exposing sensitive data! Don't just hope you filtered your objects. Enforce it at the type level! Here's how TypeScript's Pick utility type acts as your security guard. It lets you create a "safelist" of properties. #code #coding #programming #softwareengineering

  • image is a screenshot of code and this is the code.
interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  createdAt: Date;
  updatedAt: Date;
  isAdmin: boolean;
}

/* 
  We will use Pick to define our safely exposed user data and prevent
  accidental exposure of sensitive fields.
  No sensitive fields are exposed like passwordHash or isAdmin.
*/

type PublicUser = Pick<User, 'id' | 'name' | 'email'>;
function getPublicUsers(db: { user: User[] }): PublicUser[] {
  return db.users.map(user => ({
    id: user.id,
    name: user.name,
    email: user.email,
    // TRYING TO GET DATA THAT COULD POTENTIALLY BE EXPOSED?
    passwordHash: user.passwordHash,  // ❌ TypeScript ERROR - not in the Pick type!
    isAdmin: user.isAdmin,            // ❌ TypeScript ERROR - not in the Pick type!
  }));
}

Exactly! 🛡️ TypeScript’s Pick is like having a bouncer at the club door only the properties you explicitly allow get through. It’s a simple but powerful way to prevent accidental leaks of sensitive data, enforce compile-time safety, and reduce those “oops” moments in production. Danny Thompson

Like
Reply

To view or add a comment, sign in

Explore content categories