Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 让TS抱怨与不可为空的字段进行空比较?_Javascript_Typescript - Fatal编程技术网

Javascript 让TS抱怨与不可为空的字段进行空比较?

Javascript 让TS抱怨与不可为空的字段进行空比较?,javascript,typescript,Javascript,Typescript,有没有办法让TS对此进行投诉?我有检查 const foo: string = 'asdf'; if (foo !== null) { console.log(foo); } 例如,如果我将该条件更改为: if (foo !== 42) { 我得到: 此条件将始终返回“true”,因为类型“string”和“number”没有重叠 您不能使用==导致错误,因为TS具有特殊的切口,可以与null/未定义的进行比较 如果愿意使用helper函数,可以使用条件类型确保null是测试表达式

有没有办法让TS对此进行投诉?我有
检查

const foo: string = 'asdf';

if (foo !== null) {
    console.log(foo);
}
例如,如果我将该条件更改为:

if (foo !== 42) {
我得到:

此条件将始终返回“true”,因为类型“string”和“number”没有重叠


您不能使用
==
导致错误,因为TS具有特殊的切口,可以与
null
/
未定义的
进行比较

如果愿意使用helper函数,可以使用条件类型确保
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)) { }
函数isNull(x:T):null扩展了T?布尔值:void{
返回(x==null)为任意值;
}
//错误
声明常量a:string;
如果(isNull(a)){}
//嗯
声明常量b:string | null;
如果(isNull(b)){}

您可以将TSLint与@RobbieMilejczak一起使用--
TSLint
不是我们的选项,不幸的是:(但我担心这可能是唯一的答案如果你使用
ESLint
你可能会用它重新创建相同的效果,但你必须自己编写规则。我很想知道为什么会存在这种例外情况如果有人拥有该信息,似乎这一定是有意的设计选择