I am attempting to implement conditional type logic for the parameter types of a callback function.
In this scenario, the first argument represents the value while the second argument could be an error message.
type CallbackWithoutError = (value: string, error: undefined) => void
type CallbackWithError = (value: undefined, error: string) => void
declare const foo: (cb: CallbackWithError | CallbackWithoutError) => void
// Assuming CallbackWithError initially
foo((value, error) => {
if (error) {
// handle error
return
}
// Switching to CallbackWithoutError after checking for error
console.log(value)
})
Is it feasible for TypeScript to assume that the callback function has the parameters related to errors defined first?
The code snippet shows how the presence of the 'error' parameter determines which type of callback (with or without error) will be used in subsequent operations.