英文:
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<T, U>(objA: T, objB: U) {
return Object.assign(objA, objB);
}
const mergeObject = marge({ fname: "Saiki" }, { lname: "Kusuo" });
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<T extends object, U>(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: "Kusuo" })
marge(1, { lname: "Kusuo" })
marge("hello", { lname: "Kusuo" })
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<T extends string>(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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论