How can I make the compiler understand that the return type of the parse method is linked to the input of the serialize method and it is dynamic?
type QUESTION = {
parse: (value: string) => any
serialize: (value: ReturnType<QUESTION['parse']>) => string
}
const idsQuestions: QUESTION[] = [
{
parse: (input) => input.split('\n'),
serialize: (ids) => ids.join('\n') // expect ids to be interpreted as string[]
},
{
parse: (input) => input.split('\n').reduce((acc, id) => ({
...acc,
[id]: true,
}), {}),
serialize: (ids) => Object.keys(ids).join('\n') // expect ids to be interpreted as { [string] => boolean }
}
]
// expect this to throw an error on build
const questionWithError: QUESTION = {
parse: () => false, // return type is boolean
serialize: (ids) => ids.join('\n') // but ids is not interpreted as boolean, so compiler doens't give an error
}
I've tried some uses of generics and unknown, but could not make it work.
Tried to use infer also, but could not understand exactly how to work with it
I could have something hardcoded like this, but I wanted it to be dynamic
type QUESTION<T> = {
parse: (value: string) => T
serialize: (value: T) => string
}
const idsQuestions: [
QUESTION<string[]>,
QUESTION<{ [k: string]: boolean }>,
] = [
{
parse: (input) => input.split('\n'),
serialize: (ids) => ids.join('\n') // expect ids to be interpreted as string[]
},
{
parse: (input) => input.split('\n').reduce((acc, id) => ({
...acc,
[id]: true,
}), {}),
serialize: (ids) => Object.keys(ids).join('\n') // expect ids to be interpreted as { [string] => boolean }
}
]
QUESTION<T>and then useTas parameter andT[]as return type for parse, and upside down for serialize?expect ids to be interpreted as { [string] => boolean }what do you mean it's not supposed to throw an error.() => falseright below have an error