【问题标题】:Infer callback parameter type based on function parameter根据函数参数推断回调参数类型
【发布时间】:2020-05-07 08:58:11
【问题描述】:
    type SeveralTypes = type0 | type1 | type2;
    function funTypes<T extends SeveralTypes>(info: T, callback: (obj: T extends type2 ? number : string) => void) {
        if (isType0(info)) {
            return callback("passAstring");  // TS Warn: Argument of type '"passAstring"' is not assignable to parameter of type 'T extends boolean ? number : string'

        } else if (isType1(info)) {
            return callback("passAstring"); // TS Warn: Argument of type '"passAstring"' is not assignable to parameter of type 'T extends boolean ? number : string'

        } else {
            return callback(1001); // TS Warn: Argument of type '1001' is not assignable to parameter of type 'T extends boolean ? number : string'
        }
    }

    funTypes(1, (d) => { });       // Typeof d --> string
    funTypes("str", (d) => { });   // Typeof d --> string
    funTypes(false, (d) => { });   // Typeof d --> number

当我使用这个函数时,参数回调的推断类型是正确的。但是 TS 在分配参数时会出现问题。有没有其他方法可以输入回调参数?

【问题讨论】:

    标签: typescript type-inference


    【解决方案1】:

    这里有几个问题。主要是缩小一个变量(在这种情况下为info)在这种情况下对另一个变量(callback)的类型没有任何影响。还有一个问题是,通常仍包含未解析类型参数的条件类型通常很难让编译器推理,因此由于 T 未知,并且您的函数采用依赖于 T 的参数,typescript 将执行安全的东西,不要让你使用number或string作为参数

    解决这个问题的常用方法是使用类型断言,或者我的首选方法,使用通用公共签名和更宽松的实现签名(请注意,确保条件类型中的逻辑由您决定在实现中被复制,这里没有编译器的帮助)

    type SeveralTypes = type0 | type1 | type2;
    function funTypes<T extends SeveralTypes>(info: T, callback: (obj: T extends type2 ? number : string) => void): void
    function funTypes(info: SeveralTypes, callback: (obj: number | string) => void) {
      if (isType0(info)) {
        return callback("passAstring");
    
      } else if (isType1(info)) {
        return callback("passAstring");
    
      } else {
        return callback(1001); 
      }
    }
    
    funTypes(1, (d) => { });       // Typeof d --> string
    funTypes("str", (d) => { });   // Typeof d --> string
    funTypes(false, (d) => { });   // Typeof d --> number
    

    Playground Link

    【讨论】:

    • 只是输入了相同的答案 :)
    • @satanTime 对不起
    猜你喜欢
    • 2020-02-28
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    相关资源
    最近更新 更多