简体   繁体   English

打字稿strictNullChecks语法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM