#Using a type in a mapped type definition

7 messages · Page 1 of 1 (latest)

leaden oyster
#

I'm trying to write a utility that would strip prefixes off of object properties and am wondering how to use that in a mapped type. I'm trying to use a mapped type, but the compiler seems to want to have a value istead of a type when declaring the key of the mapped type:

https://www.typescriptlang.org/play/?target=99&jsx=0#code/C4TwDgpgBAysBOBLMAFeEBmiAeAeAqlBNsBAHYAmAzlFQomQOYA0UAakSedbfUwHxQAvFELFSlGgAMAJAG82AX3kMMEeFAAqiqVAD8WqAC5RAKFOhIsemABKEAMYB7eBTSYcBThJ73nr3DokJlYAVzIAazInAHcyflYOcW4aIIZGQRExLkkoPxcKXFV1KABpMMjouMEDOVMoKABtOCRUdCw8crZ+AF0TfEbSntNFI3xzS2gAQWFrVvzXdw7cOQBDAH0AIyMARkVWAHINg-5TAHozhqgAPT0gA

How can you use a computed type as a key in a mapped type?

spark gullBOT
#

@leaden oyster Here's a shortened URL of your playground link! You can remove the full link from your message.

krofdrakula#0

Preview:```ts
type StripPrefix<
U extends string,
V extends string

= U extends ${V}${infer T} ? T : U

type StripRecordPrefix<
U extends Record<string, unknown>,
V extends string

= U extends Record<infer K, unknown>
? {
[StripPrefix<K, V>]: U[K]
}
: U

type A = StripRecordPrefix<{a_b: 1}, "a_">
...```

leaden oyster
#
spark gullBOT
#

@leaden oyster Here's a shortened URL of your playground link! You can remove the full link from your message.

krofdrakula#0

Preview:```ts
type StripPrefix<
U extends unknown,
V extends string

= U extends ${V}${infer T} ? T : U

type StripRecordPrefix<
U extends Record<string, unknown>,
V extends string

= U extends Record<infer K, unknown>
? {
[P in keyof U as StripPrefix<K, V>]: U[K
...```

radiant cedar
#
type StripRecordPrefix<
  U extends Record<string, unknown>,
  V extends string,
> = {
    [P in keyof U as StripPrefix<P, V>]: U[P]
  };

@leaden oyster

#

In your code, K is the union of all keys, whereas P would be one key at a time
Use that one key to index into U
Using union of keys gives union of values

leaden oyster
#

ah, yes, that does it, thanks!