I am trying to dynamically map one type to another based on certain flags, which might result in optional fields.
type Constraint = {
required: boolean,
callback: () => any,
}
type Schema = Record<string, Constraint>;
const mySchema: Schema = {
bar: {
required: true,
callback: () => 1
},
foo: {
required: false,
callback: () => true
}
}
type MapSchemaToOutput<T extends Schema> = {
[K in keyof T as T[K]['required'] extends true ? K : never]: ReturnType<T[K]['callback']>
} & {
[K in keyof T as T[K]['required'] extends false ? K : never]?: ReturnType<T[K]['callback']>
}
type Output = MapSchemaToOutput<typeof mySchema>;
The end goal is to have Output equal:
{
bar: number,
foo?: boolean
}
I know I can do the mapping by hand, interested to know if this can be done dynamically.