typescriptrecord

How to match typescript Record value with the key?


interface User {
  email: string;
  name: string;
}

const UserRecord = Record<keyof User, keyof User> {
  email: 'email',
  name: 'name',
};

My problem with the above code that it's not typesafe for the values, so I could even do:

const UserRecord = Record<keyof User, keyof User> {
  email: 'name',
  name: 'email',
};

Solution

  • You can use mapped types:

    interface User {
      email: string;
      name: string;
    }
    
    const UserRecord: {
      [x in keyof User]: x
    } = {
      email: 'email',
      name: 'name',
    };