#Indexed access types with generics

13 messages · Page 1 of 1 (latest)

vague pecanBOT
#

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

8180e#0

Preview:```ts
const formatters = {
str: (data: unknown) => String(data),
nb: (data: unknown) => Number(data),
bool: (data: unknown) => Boolean(data),
}

function fn<T extends keyof typeof formatters>(
formatter: T,
handler: (
data: ReturnType<typeof formatters[T]>
) => unkno
...```

potent phoenix
#

You are using formatters like a mapped type, so you should give it a type like mapped type for TS to understand what you are trying to do.

#

Here's one way to do it:

vague pecanBOT
#
nonspicyburrito#0

Preview:```ts
type FormatterMap = {
str: string
nb: number
bool: boolean
}

const formatters: {
[K in keyof FormatterMap]: (
data: unknown
) => FormatterMap[K]
} = {
str: data => String(data),
nb: data => Number(data),
bool: data => Boolean(data),
...```

narrow edge
potent phoenix
#

You can derive FormatterMap from formatters instead of the other way around

narrow edge
#

like this?

type FormatterMap = {
  [K in keyof typeof formatters]: (data:unknown) => ReturnType<typeof formatters[K]>
}
potent phoenix
#

Yeah

narrow edge
#

it doesn't work

potent phoenix
#

You still need to turn formatters into a mapped type afterwards.

vague pecanBOT
#
nonspicyburrito#0

Preview:```ts
const formatters = {
str: (data: unknown) => String(data),
nb: (data: unknown) => Number(data),
bool: (data: unknown) => Boolean(data),
}

type FormatterMap = {
[K in keyof typeof formatters]: ReturnType<
typeof formatters[K]

}

const _formatters: {
[K
...```