函数如何在打字稿中检查空值?

oli*_*ver 2 javascript typescript

在打字稿 2.6 中,我想编写一个执行空检查的函数。当我启用严格的空检查时,打字稿 2.6 会抱怨以下代码。(注意,当使用空检查时直接有效)

编辑:更正,notNullOrUndefined因为它没有检查 foo

interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): boolean => {
  return a.foo != null;
}
const len = (a: A): number => {
  //if (a.foo != null) {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
} 
Run Code Online (Sandbox Code Playgroud)

这是要玩的示例:示例

解决这个问题的打字稿方法是什么?

jca*_*alz 7

编辑:更新以反映修复有问题的错字: 这个问题有点令人困惑,因为您notNullOrUndefined()根本没有检查a.foo,所以这些会有所不同也就不足为奇了。

请注意,使用--strictNullCheckson 时,您已定义len()a参数是 an A,因此不能为 null 或未定义。所以你不必alen()函数实现中检查自己;相反,您需要确保传递给的任何内容len()都是有效的A. SonotNullOrUndefined()是一个坏名字,因为您正在检查foo参数的值,而不是参数本身。随意将其更改为类似的内容fooPropertyIsNotNull();我暂时离开它。

这里的主要问题是 TypeScript 识别出这if (a.foo != null) { ... }是一个类型保护,并缩小a.foo到子句string内部{ ... }。但是类型保护不会自动从函数中传播出去,所以 TypeScript 不理解它notNullOrUndefined()本身充当类型保护。

幸运的是,这个问题很常见,TypeScript 提供了用户定义的类型保护:如果你有一个函数返回 aboolean缩小其一个参数的类型,你可以使用语法将boolean返回类型更改为类型谓词x is T。这是为了notNullOrUndefined()

const notNullOrUndefined = (a: A): a is { foo: string } => {
  return a.foo != null;
}
Run Code Online (Sandbox Code Playgroud)

所以函数签名说:如果你传入 an A,它将返回一个布尔值。如果它返回true,则传入的参数会缩小为{ foo: string }。现在你不会得到任何错误,如你所愿:

interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): a is { foo: string } => {
  return a.foo != null; // checking a.foo
}
const len = (a: A): number => {
  if (notNullOrUndefined(a)){
    return a.foo.length; // okay
  }
  return 0;
} 
Run Code Online (Sandbox Code Playgroud)

希望能帮到你,祝你好运!