代码之家  ›  专栏  ›  技术社区  ›  quinn

Typescript无法检测非空类型

  •  -1
  • quinn  · 技术社区  · 7 年前

    这是我在VS代码中遇到的错误:

    enter image description here

    我尝试了很多不同的方法,最后是最明确的 selectedDate !== null

    实际代码:

    selectedDate !== null ? selectedDate.getTime() === day.getTime() : false
    

    var从 render() 方法如下:

    const { selectedDate } = this.state

    并且状态在类中定义如下:

    state = {
      selectedDate: null
    }
    

    由于它在这里为null,并且作为常量加载,我猜typescript假定它只能为null。即使它不等于null。

    3 回复  |  直到 7 年前
        1
  •  2
  •   Jesse Hallett    7 年前

    看起来你已经申报了 selectedDate 与类型 null const selectedDate: null . 使用 无效的 无效的 还有另一种。

    请注意,使用 const

        2
  •  1
  •   zedryas    7 年前

    你能 selectedDate 变量可以是 null ?

    如果没有,, 但要小心使用 ,并且仅当您确定变量永远不能为null时,才使用 猛敲 这样的属性:

    selectedDate!.getTime ()

    注意 ! 选定日期

        3
  •  0
  •   zedryas    7 年前

    你试过了吗

    state = {
      selectedDate: undefined
    } as {
      selectedDate?: Date
    }
    
    推荐文章