从参数派生的函数结果类型,不进行强制转换

时间:2020-08-13 05:02:23

标签: typescript

在以下代码中:

function fourtyTwo<T extends boolean>(num: T): T extends true ? number : string {
    if (num) {
        return 42;
    } else {
        return 'fourty-two';
    }
}

我得到2个相同错误的实例:

  1. Type '42' is not assignable to type 'T extends true ? number : string'.ts(2322)
  2. Type '"fourty-two"' is not assignable to type 'T extends true ? number : string'.ts(2322)

有没有一种方法可以在不转换返回类型的情况下使它正常工作?

0 个答案:

没有答案