IQbrod
IQbrod

Reputation: 2265

Typescript callback type with optional error parameter

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"));

Upvotes: 0

Views: 234

Answers (1)

Luke-zhang-04
Luke-zhang-04

Reputation: 793

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.

Upvotes: 1

Related Questions