【问题标题】:Flowtype: Cannot assign X to Y because property Y is missing in nullFlowtype:无法将 X 分配给 Y,因为 null 中缺少属性 Y
【发布时间】:2019-02-19 23:28:39
【问题描述】:

一个相对简单的问题,但我一直以各种形式遇到。

这是一个示例(使用try-flow 进行测试):

import * as React from 'react';

type Props = {
    value: string | number 
}

export default class Example extends React.Component<Props> {
    _hiddenInput: { current: React.ElementRef<'input'> | null };
    value(val: number) {
        if (this._hiddenInput.current !== null) {
            this._hiddenInput.current.value = String(1234);
        }
    }
}

这里的_hiddenInput.current 是一个"maybe-type" 对象属性,它似乎没有通过if-not-null 检查得到适当的改进。

你们会怎么解决这个问题?

【问题讨论】:

  • 您的代码应张贴在此处,以便人们现在可以看到它,以便为您和以后遇到类似问题的其他人提供帮助。
  • ^ 缺少链接@Pointy
  • 链接不够。无法保证外部资源会持续存在。请查看site tour,尤其是“如何提问”的说明。
  • 哦,我的错,我以为您的 here 格式有误。

标签: javascript flowtype


【解决方案1】:

这是因为 Flow 不知道 String 函数可能有什么副作用,所以当您调用 String(1234) 时,this._hiddenInput.current !== null 细化无效(这发生在赋值之前)。考虑这个人为的例子:

export default class Example extends React.Component<Props> {
  _hiddenInput: { current: React.ElementRef<'input'> | null };
  value(val: number) {
    if (this._hiddenInput.current !== null) {
       this._hiddenInput.current.value = String(1234);
    }
  }
}

const example = new Example();
example._hiddenInput = { current: elementRef };

window.String = function(input) {
  example._hiddenInput.current = null;
  return `${input}`;
};
// Throws, because the String-function above will be called between
// refining the nullable type and assigning to it.
example.value(1)

您可以用 Flow 知道没有副作用的东西替换函数调用

this._hiddenInput.current.value = `${1234}`

或者你可以在分配给它的属性之前将容器对象“保护”到一个局部变量中

const {current} = this._hiddenInput
if (current !== null) {
  current.value = String(1234);
}

请参阅文档中的 Refinement Invalidations
当然,String 函数实际上并没有做这样的事情,但目前 Flow 没有任何办法知道这一点。有一个feature request 可以将函数标记为,这可能会有所帮助。

【讨论】:

  • 啊!我知道答案不可避免地会像问题本身一样(相对)简单——只是 Flow 将我指向一个完全不同的地方!非常感谢。
猜你喜欢
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 2021-11-21
  • 2018-11-05
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多