0

This is my current code

type Callback<T> = (t:T, err?: Error) => void;

foo(callback: Callback<string>) {
    callback("Hello World"); // Data
    callback(null, new CustomError("Hello world")); // Error
}

// usage
foo((name: string, err: Error) => {
    // Stuff here
});

Which type would be correct so I'm able to send both error and data as the only parameter ?

callback("Hello World");
callback(new CustomerError("Hello World"));
2
  • please share full example Commented Mar 13, 2021 at 17:43
  • If the callback is only called once let foo() return a Promise, if it is called multiple times let foo() return an Observable. Commented Mar 13, 2021 at 20:13

1 Answer 1

1

From what I understand, this is what you want

type Callback<T> = (dataOrError: T | Error) => void

function foo(callback: Callback<string>) {
    callback("Hello World"); // Data
    callback(new Error("An error occured")); // Error
}

// usage
foo((dataOrError) => {
    if (dataOrError instanceof Error) {
        // Handle Error

        return;
    }

    // Handle data
    // Typescript knows this is a string because its only other type is Error,
    // which would've terminated the function
    console.log(dataOrError);
});

This is admittedly a weird way to handle callbacks, but I guess it works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.