【问题标题】:Flow: Cannot get ... because property ... is missing in object literal流程:无法获取...因为对象文字中缺少属性...
【发布时间】:2019-06-18 16:09:23
【问题描述】:

我有以下代码,应该使用 JavaScript 的 in 运算符优化 example 变量的类型:

type Example = 'foo' | 'bar' | 'baz';

const objectWithSomeExampleKeys = {
  foo: 'foo',
  baz: 'baz'
};

function heresTheProblem(example: Example): void {
  if (example in objectWithSomeExampleKeys) {
    objectWithSomeExampleKeys[example];
  }
}

但是,我收到以下错误:

    10:     objectWithSomeExampleKeys[example];
                                      ^ Cannot get `objectWithSomeExampleKeys[example]` because property `bar` is missing in object literal [1].
        References:
        3: const objectWithSomeExampleKeys = {
                                             ^ [1]

如何让 Flow 识别 example 不能是 bar 或不在 objectWithSomeExampleKeys 中的任何其他属性?

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    我找到了解决这个问题的方法:

    如果我使用 {[example: Example]: string} 从示例代码中显式键入 objectWithSomeExampleKeys,错误就会消失:

    type Example = 'foo' | 'bar' | 'baz';
    
    // Explicit type added to objectWithSomeExampleKeys:
    const objectWithSomeExampleKeys: {[example: Example]: string} = {
      foo: 'foo',
      baz: 'baz'
    };
    
    function heresTheProblem(example: Example): void {
      if (example in objectWithSomeExampleKeys) {
        objectWithSomeExampleKeys[example];
      }
    }
    

    https://flow.org/try/#0C4TwDgpgBAogHgQwLZgDbQLxQOQDMD2+2UAPjgEYIBOxZ2lAXtgNwBQrAxvgHYDOwUfOQBWEDsADqAS2AALAMr4kEeMjQQA0hBC8AXFADeAbQiIU6favMQAuvv5Up3AOYBfKFgOsoUAvn14hNgANN5QjAGM2KyubKy4AK7c4lI8ULIQVBC8ACoZAApUQuhIABSmahawZuoAlPoAbvhSACaGYVK4UOU16FBOgiJikjIKSiq9mtq8te0+PkKi4tJyispW6lo6JpM2bD6uMUA

    【讨论】:

      【解决方案2】:

      问题是示例可以是'bar',因为示例的类型是'foo' | 'bar' | 'baz'。这样检查没问题:https://flow.org/try/#0C4TwDgpgBAogHgQwLZgDbQLxQOQDMD2+2UAPjgEYIBOxZ2lAXtgNwBQrAxvgHYDOwUfOQBWEDsADqAS2AALAMr4kEeMjQQA0hBC8oWAN6soUAvgBcOU9gA0RqIwv0ETW8cpVH77KwC+bVrgArtziUjxQshBUELwAKpEAClRC6EgAFBCIKOgW-FRS3ADmAJQWAG74UgAmUIbGUrhQGVnqUAWCImKSMgpKKi3oWjrFtXbGQqLi0nKKyqrZmtq8ANqZaugAumzGPr5AA

      type Example = 'foo' | 'bar' | 'baz';
      
      const objectWithSomeExampleKeys = {
        foo: 'foo',
        baz: 'baz',
        bar: 'bar'
      };
      
      function heresTheProblem(example: string): void {
        if (example in objectWithSomeExampleKeys) {
          objectWithSomeExampleKeys[example];
        }
      }
      

      【讨论】:

      • example 可以是 bar,但在我的示例代码的 if 语句中永远不会是 bar。我希望 Flow 有一种方法可以理解 in 的语义含义,或者某种等效的改进类型的方法。
      • 流程尚未基于 in 进行优化。
      猜你喜欢
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2019-07-15
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多