简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM