'"local" generic type in a typescript mapped type
I'm using typescript mapped types to try and transform the fields of a type/class to a function that takes an argument where the type differs for each field and is determined base on the function assigned to the field:
Basically I want to map a type like:
type ArgsSchema<Args> =
Args extends string
? "string"
: Args extends number
? "number"
: Args extends Date
? typeof Date
: never
type From = {
field: string,
anotherField: boolean
}
// Map it to
type To = {
field: {
resolve: (args: number) => string,
argsSchema: ArgsSchema<number>
},
anotherField: {
resolve: (args: Date) => boolean
argsSchema: ArgsSchema<Date>
}
}
// For an object like
const to = {
field: {
resolve: (args: number) => `Hello number ${args}`,
argsSchema: "string"
},
anotherField:
{
resolve: (args: Date) => args.getSeconds() > 10,
argsSchema: Date
}
}
I've tried the following, but it fails because it tries to infer the Args type to a single type, not a per field type.
type MapTest<Args> = {
[Key in keyof From]: {
resolve: (args: Args) => From[Key],
argsSchema: ArgsSchema<Args>
}
}
function map<Args>(mt: MapTest<Args>): void {
}
map({
field: {
resolve: (args: number) => "hello",
argsSchema: "number"
},
anotherField: {
resolve: (args: string) => true,
argsSchema: "string"
}
})
I've also tried a type variable on the function itself, but it has an error saying it that it's not assignable.
type MapTest2 = {
[Key in keyof From]: {
resolve: <Args> (args: Args) => From[Key],
argsSchema: ArgsSchema<Args>
}
}
function map2(mt: MapTest2): void {
}
map2({
field: {
resolve: (args: number) => "hello",
argsSchema: "number"
},
anotherField: {
resolve: (args: string) => true,
argsSchema: "string"
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
