[英]Getting TS to complain about null comparison to a non-nullable field?
Is there a way to get TS to complain about this? 有没有办法让TS对此进行投诉? I have
strictNullChecks
on 我有
strictNullChecks
const foo: string = 'asdf';
if (foo !== null) {
console.log(foo);
}
If, for instance, I change that condition to: 例如,如果我将条件更改为:
if (foo !== 42) {
I get: 我得到:
This condition will always return 'true' since the types 'string' and 'number' have no overlap.
由于类型“字符串”和“数字”没有重叠,因此此条件将始终返回“ true”。
You can't cause an error with ===
because TS has special carve-outs that make comparison with null
/ undefined
always allowed. 您不能使用
===
引起错误,因为TS具有特殊的分割,可以始终与null
/ undefined
进行比较。
If you're willing to use a helper function, you can use a conditional type to ensure that null
is a possible value of the tested expression: 如果您愿意使用辅助函数,则可以使用条件类型来确保
null
是被测试表达式的可能值:
function isNull<T>(x: T): null extends T ? boolean: void {
return (x === null) as any;
}
// Error
declare const a: string;
if (isNull(a)) { }
// OK
declare const b: string | null;
if (isNull(b)) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.