Why don't I get the type inference correctly here?
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAZiATgWwIZSgU0RGBeGAbwCgYZpEAuGACgBN1VqBXMAazBAHcwBKfAHwwAylEQBLMAHN6jXgBpSMMACNqsqExisO3PoJgA5ZshXYNqBUpUgQAG3UNNLdpx788QgEK27mVGAWVgC+ANzExHCswFDi4PBgADwAKjCYAB5YYHS4bJgAniBwMFD5AA6YRfBIaBjYEAI0Sggo6FhUMMmKZAAWAXR+HRbUAEqYUMyIYMnlmIk0pRVVLbXtELwA2skAugIeQjpuYIr8JGSgkLBOqPhEYUp92YM0K231G691iNtBvOHBQA
#Indexed access types with generics
13 messages · Page 1 of 1 (latest)
@narrow edge Here's a shortened URL of your playground link! You can remove the full link from your message.
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
...```
You can choose specific lines to embed by selecting them before copying the link.
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:
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),
...```
You can choose specific lines to embed by selecting them before copying the link.
is there another way to do by infering the return types? because i have a very complex type and i need inference
You can derive FormatterMap from formatters instead of the other way around
how to do that?
like this?
type FormatterMap = {
[K in keyof typeof formatters]: (data:unknown) => ReturnType<typeof formatters[K]>
}
Yeah
it doesn't work
You still need to turn formatters into a mapped type afterwards.
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
...```
You can choose specific lines to embed by selecting them before copying the link.