[英]Typescript strictNullChecks syntax
I'm using the strictNullChecks
flag in my Typescript project. 我在Typescript项目中使用
strictNullChecks
标志。
Consider the function below: 考虑以下功能:
function hello(a: string | null) {
if (a !== null) {
console.log(a.length); // Here, "a" can only be a string
}
}
The compiler works perfectly here. 编译器在这里可以完美工作。
However if I write instead if (typeof a !== "null")
or even lodash's if (!_.isNull(a))
the compiler won't understand and will complain that a
can possibly be null
. 但是,如果我改写
if (typeof a !== "null")
甚至lodash的if (!_.isNull(a))
,编译器将无法理解,并且会抱怨a
可能为null
。
Is there any way to have these alternative syntaxes work too? 有没有办法使这些替代语法起作用?
However if I write instead
if (typeof a !== "null")
or ... the compiler won't understand and will complain that a can possibly be null.但是,如果我改写
if (typeof a !== "null")
或...,编译器将无法理解,并且会抱怨a可能为null。
This is a good thing because typeof null === "object"
, not "null"
. 这是一件好事,因为
typeof null === "object"
,而不是"null"
。 TypeScript does not consider non-working ways of testing for null
to be correct. TypeScript认为
null
测试方法是不正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.