'Typescript argument type errors when using generic but hard coding possible values from the generic does not
I'm trying to write a simple mapper function to convert values of a specific type to another type. Here's what I have
const profiles = {
string: {
date: (string: string): Date => new Date,
},
date: {
string: (date: Date): string => date.toISOString()
}
}
type Profiles = typeof profiles
type mappers<T extends keyof Profiles> = Profiles[T][keyof Profiles[T]]
function map<T extends keyof Profiles>(type: T, source: Parameters<mappers<T>>[0], destination: keyof Profiles[T]) {
}
In the type for the argument source its using the generic T. And it errors saying
Type '{ string: { date: (string: string) => Date; }; date: { string: (date: Date) => string; }; }[T][string]' is not assignable to type '(...args: any) => any'.
But if I hover over T it has the type "string" | "date" and if I hard code either of those values in place of T it works as I would expect. It even catches if I use something other than "string" | "date" as I would expect.
So why does it work with the values that T can be but not with T itself?
Playground (thanks @md2perpe)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
