【问题标题】:Optional generic type with TypeScript带有 TypeScript 的可选泛型类型
【发布时间】:2018-07-15 21:07:59
【问题描述】:

我有 is generic 函数类型:

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

该类型可以这样使用:

const v = function(cb: EVCb<boolean>){
   cb(null, true);  // compiles correctly
};

const v = function(cb: EVCb<boolean>){
   cb(null, 'yo');  // does not compile 
};

但我想知道是否有办法为错误参数添加optional 类型,因为现在它总是any。像这样:

export type EVCb<T, E?> = (err: E | any, val?: T) => void;

用户会这样使用它:

EVCb<boolean, Error>

或者他们可以选择省略第二个参数,然后这样做:

EVCb<boolean>

这有可能吗?

【问题讨论】:

    标签: typescript typescript2.0 tsc


    【解决方案1】:

    如果您为其提供默认值,则类型参数可以是可选的:

    export type EVCb<T, E = any> = (err: E, val?: T) => void;
    

    【讨论】:

    • 这会删除错误,但输入的错误类型不是根据输入类型自动定义的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多