简体   繁体   中英

TypeScript create generic callback type

Say I have this function definition:

export type ErrorValueCallback = (err: any, val?: any) => void;

a standard callback interface. And I can use it like so:

export const foo = function(v: string, cb:ErrorValueCallback){
    cb(null, 'foo');
};

But what if want to make this callback generic, something like this:

export type EVCallback = <T>(err: any, val: T) => void;

that syntax works, but when I try to use it:

export const foo = function(v: string, cb:ErrorValueCallback<string>){
    cb(null, 'foo');
};

I get an error

ErrorValueCallback is not generic

how do I what I am looking to do?

You need to add the generic to the type type ErrorValueCallback<T>

Fixed example

export type ErrorValueCallback<T> = (err: any, val: T) => void; // FIX

export const foo = function(v: string, cb:ErrorValueCallback<string>){
    cb(null, 'foo');
};

I think you wanted to use EVCallback instead

export type EVCallback<T> = (err: any, val: T) => void;

like this:

export const foo = function(v: string, EVCallback<string>){
    cb(null, 'foo');
};

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