代码之家  ›  专栏  ›  技术社区  ›  Ryan Wheale

FlowJS-由于无法识别“typeof”语句的结果,因此出现类型错误

  •  0
  • Ryan Wheale  · 技术社区  · 6 年前

    以下代码导致错误:

    type NextItem = string | { [string]: string };
    
    const next: NextItem = 'foo';
    const isString = typeof next === 'string';
    const toName = isString ? next : Object.keys(next)[0];
                                     ^ string [1] is not an object.
    

    isString 变量修复它:

    type NextItem = string | { [string]: string };
    
    const next: NextItem = 'foo';
    const toName = typeof next === 'string' ? next : Object.keys(next)[0];
    

    为什么? ,但我希望有人能提供更好的解决方案。我需要重新使用 变量,并希望保持我的代码既干燥和简单(易于阅读)。所以请不要用“聪明”的方法。

    1 回复  |  直到 6 年前
        1
  •  1
  •   loganfsmyth    6 年前

    Flow的改进通常基于使用时的直接检查,因此它只会看到您的 isString 变量作为 boolean 没有特别的意义。

    • 调整代码的控制流,以便有两个明确的分支,假设有更多的检查 ,您可以随时明确分支来处理这两种情况。
    • typeof next === 'string' 检查。

      const toName = typeof next === 'string' ? next : Object.keys(next)[0];
      
    • predicate function isString公司

      function isString(arg: mixed): boolean %checks {
         return typeof arg === "string"; 
      }
      
      const toName = isString(next) ? next : Object.keys(next)[0];