I'm trying to write a function such that the first parameter is boolean, and depending on whether this argument is true or false, the second argument is a function that accepts either a string or string[].
Here is my attempt:
type P<B extends boolean> = B extends true ? string[] : string
function callback<B extends boolean>(b: B, t: (f: P<B>) => void) {
const file = 'file'
if (b) {
t([file]) // <-- Error: Argument of type 'string' is not assignable to parameter of type 'P<B>'.
} else {
t(file) // <-- Error: Argument of type 'string[]' is not assignable to parameter of type 'P<B>'.
}
}
callback(false, (f: string) => {}) // <-- No problem, resolves the correct argument type
callback(true, (f: string[]) => {}) // <-- No problem, resolves the correct argument type
This works for resolving the correct argument types when the function is called. However, inside the function, the TS compiler is giving me an error that it cannot resolve the conditional type to either string or string[]. What is the correct way to do this?