#Add prefix to literal type in union type of objects?

14 messages · Page 1 of 1 (latest)

placid lotus
#

I have a union type of multiple event objects:

type Event = { type: 'foo' } | { type: 'bar'; userId: string } // etc...

I now want to create a type, that is the same union type as Event, but where each type property is prefixed. Like:

type PrefixedEvent = { type: 'user foo' } | { type: 'user bar'; userId: string } // etc...

is that possible?

cerulean tapir
#

@placid lotus This should work:

type MapToUserEvent<T extends Event> = T extends { type: infer Type extends string } ? Omit<T, "type"> & { type: `user ${Type}`} : never;

type PrefixedEvent = MapToUserEvent<Event>
placid lotus
#

I knew I needed to use infer somehow 🙂

#

Thanks

sand ledge
#

if you use a mapped type approach you wouldn't need infer im pretty sure

#

just fyi

placid lotus
#

@sand ledge I tried with mapped type but didn't get it to work. Can you show me how?

hollow oxideBOT
#
that_guy977#0

Preview:```ts
type Event_ = { type: 'foo' } | { type: 'bar'; userId: string } // etc...

type Prefixed<T extends { [key in TargetKey]: string }, TargetKey extends string, Prefix extends string> = {
[K in keyof T]: K extends TargetKey ? ${Prefix}${T[K]} : T[K]
}

type PrefixedEvent = Prefixed<Event_, "type", "user "> // { type: 'user foo' } | { type: 'user bar'; userId: string } // etc...
...```

sand ledge
#

this is one possible approach

#

(mine looks a lot different from retsam's due to it being really generic, a more specific implementation that just changes the extraction could look like this:

hollow oxideBOT
#
that_guy977#0

Preview:```ts
type Event_ = { type: 'foo' } | { type: 'bar'; userId: string } // etc...

type Prefixed<T extends Event_> = {
[K in keyof T]: K extends "type" ? user ${T[K]} : T[K]
}

type PrefixedEvent = Prefixed<Event_> // { type: 'user foo' } | { type: 'user bar'; userId: string } // etc...
...```

sand ledge
#

just for the sake of comparison)

placid lotus
#

Thank you very much!

#

I prefer you type because the resulting type is much easier to read