带条件类型的简单函数 [英] Simple function with conditional type

查看:24
本文介绍了带条件类型的简单函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下功能主要取自 打字稿手册部分使用条件类型,但它不起作用:

The following function was largely lifted from the typescript handbook section on using conditional types, yet it doesn't work:

function test<T extends boolean>(a: T): T extends true ? string : number {
  return a ? '1' : 1
}

Typescript 报告:

Typescript is reporting that:

Type '1 | "1"' is not assignable to type 'T extends true ? string : number'.
  Type '1' is not assignable to type 'T extends true ? string : number'.

我想我遗漏了一些明显的东西.如何构造此函数,以便 typescript 根据函数的参数正确推断类型?

I imagine I'm missing something obvious. How can I construct this function so that typescript correctly infers the type based on the function's argument?

我意识到可以使用函数签名重载来解决这个特定问题,但我想了解更多关于条件类型的信息.

I realize that this specific problem could be solved using function signature overloading, but I'd like to learn more about conditional types.

推荐答案

简而言之,您不能.无法为未解析的条件类型(仍然依赖于自由泛型类型变量的条件类型)分配任何值.您唯一能做的就是使用类型断言.

The short a answer is you can't. No value will be assignable to an unresolved conditional type (a conditional type that still depends on a free generic type variable). The only thing you can do is use a type assertion.

function test<T extends boolean>(a: T): T extends true ? string : number {
  return (a ? '1' : 1)  as any
}

条件类型对于表达参数之间的关系很有用,但在实现函数时却无济于事.另一种方法是使用更宽松的实现签名.

Conditional types are useful to express relations between parameters but they don't help when it comes to implementing the function. Another approach would be to use a more permissive implementation signature.

function test<T extends boolean>(a: T): T extends true ? string : number
function test(a: boolean): number | string {
    return (a ? '1' : 1)
}

这篇关于带条件类型的简单函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆