Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map values in Typescript?

I am trying to make an enrich-object function, but I can't figure out how to change the type of the values inside a Type.

So given the following types

{ a: string, c: number }
{ a: boolean, b: Cow }

I want the returned type to respectively be

{ a: Container<string>, c: Container<number> }
{ a: Container<boolean>, b: Container<Cow> }

The closest I've gotten is using the Record util

enrich<T>(value: T) {
  // create mapped object by iterating over object keys
  return container as Record<T, Container<any>>
}

But that changes all of the objects value types to Container<any>, erasing part of the context from the input.

like image 570
Tezra Avatar asked Oct 15 '25 19:10

Tezra


1 Answers

You can use mapped types for this:

type Enrich<T> = {[key in keyof T]: Container<T[key]>};
like image 166
Matt Timmermans Avatar answered Oct 18 '25 10:10

Matt Timmermans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!