TypeScript 创建通用回调类型

TypeScript create generic callback type

假设我有这个函数定义:

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

一个标准的回调接口。我可以这样使用它:

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

但是如果想让这个回调通用化怎么办,就像这样:

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

该语法有效,但当我尝试使用它时:

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

我收到一个错误

ErrorValueCallback is not generic

我该怎么做?

我想你想改用 EVCallback

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

像这样:

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

您需要将泛型添加到 类型 type ErrorValueCallback<T>

固定示例

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

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