[英]Typescript generics: types 'T' and 'number' have no overlap error
Consider this example:考虑这个例子:
function foo<T>(t: T): boolean {
return t === 1;
}
I get This condition will always return 'false' since the types 'T' and 'number' have no overlap.
我得到This condition will always return 'false' since the types 'T' and 'number' have no overlap.
. .
The error goes away if I change it to:如果我将其更改为:
function foo<T extends any>(t: T): boolean {
return t === 1;
}
I thought T
could be any
by default, so why did I need extends any
?我认为默认情况下T
可以是any
,那么为什么我需要extends any
? Without extends any
, what type does TS expect T
to be?没有extends any
,TS 期望T
是什么类型?
Edit, actual function:编辑,实际功能:
function cleanObj<T>(
obj: ObjectOf<T>,
): ObjectOf<T> {
const newObj = {};
for (const k of Object.keys(obj)) {
if (obj[k] !== null && typeof obj[k] !== 'undefined' && obj[k] !== false) {
newObj[k] = obj[k];
}
}
return newObj;
}
The triple equals operator ===
returns true if both operands are of the same type and contain the same value.如果两个操作数的类型相同且包含相同的值,则三元等号运算符===
返回 true。 Compared to that "1" == 1
would return true.相比之下, "1" == 1
将返回 true。
Since you use ===
you also compare the type, which is number
for the right hand operant 1
.由于您使用===
您也比较类型,这是number
换右手操作性1
。 However, your T can not just be a number, that is why the compiler gives you this notification.然而,你的 T 不能只是一个数字,这就是编译器给你这个通知的原因。
Possible solutions:可能的解决方案:
==
instead of ===
使用==
而不是===
Partially taken from https://github.com/microsoft/TypeScript/issues/17445 :部分摘自https://github.com/microsoft/TypeScript/issues/17445 :
Consider your original function:考虑您的原始功能:
function compare<T>(obj: T): boolean {
return obj === 1;
}
if it would be allowed to compare anything to T
we could also write:如果允许将任何内容与T
进行比较,我们也可以这样写:
function compare<T>(obj: T): boolean {
return obj === 'some-string-thats-definitely-not-obj';
}
If you use that function inside of some if
, you could potentially create unreachable code that won't throw an error.如果在 some if
使用该函数, if
可能会创建不会引发错误的无法访问的代码。
This is why typescript requires you to explicitely tell it that T
can be any
, which is obviously unsafe for the above reason.这就是为什么打字稿要求您明确告诉它T
可以是any
,由于上述原因,这显然是不安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.