【问题标题】:TypeScript create generic callback typeTypeScript 创建通用回调类型
【发布时间】:2018-12-18 21:24:40
【问题描述】:

假设我有这个函数定义:

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 不是通用的

我该怎么做?

【问题讨论】:

    标签: javascript node.js typescript tsc


    【解决方案1】:

    我想你想改用 EVCallback

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

    像这样:

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

    【讨论】:

      【解决方案2】:

      您需要将泛型添加到 type type ErrorValueCallback&lt;T&gt;

      固定示例

      export type ErrorValueCallback<T> = (err: any, val: T) => void; // FIX
      
      export const foo = function(v: string, cb:ErrorValueCallback<string>){
          cb(null, 'foo');
      };
      

      【讨论】:

        猜你喜欢
        • 2017-07-07
        • 2021-09-27
        • 1970-01-01
        • 2012-10-19
        • 2021-02-24
        • 2019-12-29
        • 2021-11-08
        • 2016-05-28
        • 2022-01-07
        相关资源
        最近更新 更多