javascript - typescript :为什么我们不能为泛型类型分配默认值?

以下面为例。我不太确定错误消息的含义,但从逻辑上看,签名似乎是完全有效的。这只是 TS 不支持吗?

function _createNominalCollection<isOutputOrdered_T extends boolean>(
  input: nominal_T,
  processingFunc: (count: number) => number,
  orderedOutput: isOutputOrdered_T = true,
)

^^^
Type 'boolean' is not assignable to type 'isOutputOrdered_T'.
  'boolean' is assignable to the constraint of type 'isOutputOrdered_T', but 'isOutputOrdered_T' could be instantiated with a different subtype of constraint 'boolean'.ts(2322)

最佳答案

正如@VLAZ 指出的那样 _createNominalCollection<false>()是有问题的。让我们再看看这个错误:

'boolean' is assignable to the constraint of type 'isOutputOrdered_T', but 'isOutputOrdered_T' could be instantiated with a different subtype of constraint 'boolean'.ts(2322)

这意味着您传递了一个明确的 <false>类型作为通用参数,isOutputOrdered_T现在限制为 false但是默认参数是 true ,这将违反这一点。

或者换句话说,truefalseboolean 的子类型,并且您的函数允许将 bool 值限制为这些子类型之一,但不保证对该变量的赋值都属于同一子类型。

让我提出一个替代方案。


当你有一个函数根据不同的参数返回不同的类型时,你应该始终考虑是否 function overloads更适合建模而不是泛型。它们允许您以一种简单的方式专门将参数模式映射到特定的返回类型,而根本不需要任何泛型。

例如:

// sorted version
function myFn(orderedOutput?: true): 'sorted'

// unsorted version
function myFn(orderedOutput: false): 'unsorted'

// Implementation
function myFn(orderedOutput: boolean = true): 'sorted' | 'unsorted' {
  return orderedOutput ? 'sorted' : 'unsorted'
}

// Testing
const a = myFn(true) // sorted
const b = myFn(false) // unsorted
const c = myFn() // sorted

在这里,您为您的函数创建了两个签名。第一个“排序”版本不接受任何参数或 true .第二个“未排序”版本接受 false .然后您就有了一个可以处理这两种情况的实现。

Playground

关于javascript - typescript :为什么我们不能为泛型类型分配默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66604535/

相关文章:

database - 使用golang从postgres中的csv批量插入而不使用for循环

github - 如何在两个句子之间添加 Git Readme 中的 Tab 空格?

python - 如何在 Python 中将月份名称生成为列表?

html - 将样式添加到 mat-autocomplete 的 mat-option

.net-core - Cake Clean 任务在蛋糕构建时被跳过

c++ - 如果 new 运算符失败,是否可以将指针设置为 null?

postgresql - 我想用 mikro-orm 插入,但它找不到我的表 :c (TableNo

r - 合并和删除*文件之间的冗余行

regex - 为电话号码编写正则表达式

git - 使用 git rev-parse 的错误提交哈希