【问题标题】:Is there a way for typescript to infer that null values are no longer possible in an array?打字稿有没有办法推断出数组中不再可能出现空值?
【发布时间】:2019-03-01 03:28:04
【问题描述】:

我有一个数组定义如下:

const myArr: (MyType | null)[] = [];

还有一个函数如下:

const myFunc = (myObj: MyType) => /* do sth */;

如果我通过非 null 过滤 myArr,然后尝试使用 myFunc 进行映射,我得到一个编译错误,因为 MyType | null 不能分配给 MyType。我明白为什么会这样,但这是过滤器和地图代码:

class MyClass {

  private myArray: (string | null)[] = [];
  
  myFunc = (str: string) => str.toUpperCase();

  myOtherFunc = () => {
    this.myArray
      .filter(str => str !== null)
      .map(this.myFunc); // Type 'string | null' is not assignable to type 'string'.
  }

}

如果我转换过滤器的结果:

const notNullResults = this.myArray.filter(str => str !== null) as string[]

它编译得很好,但我不喜欢这样强制转换。 TypeScript 有没有办法推断过滤后的数组具有不同的类型定义?

【问题讨论】:

  • 我不认为你会解决这个问题。
  • This open suggestion 会让 TypeScript 自动推断 str => str !== null 是一个类型保护。

标签: javascript typescript


【解决方案1】:

是的,你需要一个类型保护。

const notNullResults = this.myArray.filter((str): str is string => str !== null) // string[]

请注意,我们使用 is 运算符和内置的通用 string 类型来表明我们只需要字符串

【讨论】:

  • NonNullable 从类型中删除 null。这里stringstrictNullChecks 无论如何都不包含null ....所以str is string 应该也能正常工作
  • 或者您可以使用通用版本,例如const isNotNull = <T>(value: T): value is NonNullable<T> => !!value;,然后简单地使用myArray.filter(isNotNull) 得到string[]
  • 尝试使用 NonNullable 选项.. 我错过了什么吗?获取“找不到名称 'NonNullable'”
  • 我认为它是在 TS 2.8 中添加的,请检查您的版本。
猜你喜欢
  • 2020-03-24
  • 2021-09-22
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
相关资源
最近更新 更多