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.ts451 chars18 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