map record to type in typescript

In TypeScript, you can use generics to map a record to a specific type. To do this, you would define a generic type variable that represents the keys of the record, and then use the Record type to map those keys to their values.

Here's an example:

index.ts
interface User {
  id: number;
  name: string;
  email: string;
}

const usersById = {
  123: { id: 123, name: "Alice", email: "alice@example.com" },
  456: { id: 456, name: "Bob", email: "bob@example.com" },
};

function getUserById<T extends keyof typeof usersById>(id: T): typeof usersById[T] | undefined {
  return usersById[id];
}

const user123 = getUserById(123);
console.log(user123); // { id: 123, name: "Alice", email: "alice@example.com" }
451 chars
18 lines

In this example, we have a record usersById that maps user IDs to their information. We define a generic type variable T that represents the keys of the record (123 and 456 in this case).

The getUserById function takes an id parameter of type T, and returns the value of the record at that key (typeof usersById[T]). We also define the return type as typeof usersById[T] | undefined, since the key may not exist in the record.

Finally, we call the getUserById function with the ID 123, and log the result to the console. The output is the user object for ID 123.

gistlibby LogSnag