type1

问题描述 投票:0回答:1
    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个回答
© www.soinside.com 2019 - 2024. All rights reserved.