代码之家  ›  专栏  ›  技术社区  ›  Christopher Francisco

流-缓存公共变量检查时,读取联合类型属性不起作用

  •  0
  • Christopher Francisco  · 技术社区  · 8 年前

    在里面 this example ,Flow向我们展示了根据类型读取属性的方法。

    我将其重构为如下所示,并按预期工作:

    type Success = { success: true, value: boolean };
    type Failed  = { success: false, error: string };
    
    type Response = Success | Failed;
    
    function handleResponse(response: Response) {
      const value = response.success && response.value;
      const error = !response.success && response.error;
    }
    

    但是,当公共属性是字符串时,它在执行 === 检查,但如果将检查缓存到变量中,则不会:

    type Success2 = { success: 'success', value: boolean };
    type Failed2  = { success: 'not_success', error: string };
    
    type Response2 = Success | Failed;
    
    function handleResponse(response: Response2) {
      const isSuccess = response.success === 'success';
    
      // const value = response.success === 'success' && response.value;  // WORK
    
      const value = isSuccess && response.value;  // DOESN'T WORK
    }
    

    换句话说,必须有 === 在读取变量之前检查(字面意思),不能将其包含在变量中。

    这是已知的流量限制,还是我遗漏了什么?

    1 回复  |  直到 8 年前
        1
  •  2
  •   loganfsmyth    8 年前

    是的,这是预期的行为。您在这里所指的功能是 type refinement 。该实现基于Javascript的标准流控制机制,这意味着保存测试结果并稍后使用将丢弃流可能推断出的类型信息。Flow在您的非工作示例中所知道的是 isSuccess 是一个布尔值,它不知道 true 这意味着 response.value 存在。