相关疑难解决方法(0)

带条件类型的简单函数

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

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

打字稿报告说:

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'.
Run Code Online (Sandbox Code Playgroud)

我想我错过了一些明显的东西。我怎样才能构造这个函数,以便打字稿根据函数的参数正确推断类型?

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

typescript conditional-types

5
推荐指数
2
解决办法
651
查看次数

标签 统计

conditional-types ×1

typescript ×1