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

标签 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/

相关文章:

javascript - 如何更改 Controller 中指令的值以获取 angularJS 中的新数据?

javascript - 如何创建垂直图像滚动条?

javascript - 无法使react-chartjs选项生效

javascript - 插入或拖动后重新索引对象数组的算法 'n' 放置顺序更改

typescript - 使用 Typescript 时,es6 Map() 不会编译为 es5

typescript - Firebase/typescript 问题 - 当我使用 this.ref.getAuth().password.email 时它有效但我收到 FirebaseAuthData 类型错误

typescript - 如何正确处理 Vuejs 中异步事件监听器中的拒绝错误?

Angular 语法错误 : Unexpected token P in JSON at position 0

javascript - YouTube Live Streaming API 'scheduledStartTime' 向观众显示错误的时区

reactjs - 如何在 react 中添加或删除状态数组中的项目