在TypeScript中,受限制的类型参数与不受限制的类型参数之间有什么区别?

huangapple go评论61阅读模式
英文:

What is the difference between constrained vs unconstrained type parameters in typescript

问题

The problem is solved by marge<T extends object, U>(objA: T, objB: U)

现在问题已经通过这个方式解决了:marge<T extends object, U>(objA: T, objB: U)

So I was wondering what are unconstrained type parameter and constrained type parameters

所以我想知道未受限制的类型参数和受限制的类型参数分别是什么。

英文:

I am following a tutorial about generics in typescript and came across this

function marge&lt;T, U&gt;(objA: T, objB: U) {
  return Object.assign(objA, objB);
}

const mergeObject = marge({ fname: &quot;Saiki&quot; }, { lname: &quot;Kusuo&quot; });

console.log(mergeObject.fname);

//app.ts(19, 16): This type parameter might need an `extends {}` constraint.
//app.ts(19, 16): This type parameter might need an `extends object` constraint.


The problem is solved by marge&lt;T extends object, U&gt;(objA: T, objB: U)

which led me to this

https://github.com/microsoft/TypeScript/issues/48468

Now you can't assign a unconstrained type parameter T to T extends {} or T extends object.

So I was wondering what are unconstrained type parameter and constrained type parameters

答案1

得分: 1

TL;DR: extends SOMETHING 用于确保输入具有某些属性/形状。

如果类型 T 没有受限制,那么以下是有效的:

marge(undefined, { lname: "Kusuo" })
marge(1, { lname: "Kusuo" })
marge("hello", { lname: "Kusuo" })

然而,这没有意义或将引发错误。

另一方面,如果受到限制,它将过滤掉那些无效的参数。就像以下的例子:

function printLength<T extends string>(s: T) {
  console.log(s.length)
}

如果删除了extends string,编译器将抱怨“没有 length”问题,因为在这种情况下,我们没有确保输入具有 length(是一个字符串)。

英文:

TL;DR: extends SOMETHING is used to ensure the input has some properties / shapes.


If type T is not constrained, that means the follows is valid:

marge(undefined, { lname: &quot;Kusuo&quot; })
marge(1, { lname: &quot;Kusuo&quot; })
marge(&quot;hello&quot;, { lname: &quot;Kusuo&quot; })

However, it does not make sense or will throw errors.


On the other hand, if it is constrained, it will filter out those invalid parameter. Like the following example:

function printLength&lt;T extends string&gt;(s: T) {
  console.log(s.length)
}

If extends string got removed, the complier will complain about "no length" issues, because in that case, we didn't ensure the input has a length (is a string)

huangapple
  • 本文由 发表于 2023年5月21日 16:05:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定