以下面为例。我不太确定错误消息的含义,但从逻辑上看,签名似乎是完全有效的。这只是 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
,这将违反这一点。
或者换句话说,true
和 false
是 boolean
的子类型,并且您的函数允许将 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
.然后您就有了一个可以处理这两种情况的实现。
关于javascript - typescript :为什么我们不能为泛型类型分配默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66604535/