首页 > 解决方案 > 流程:无法获取...因为对象文字中缺少属性...

问题描述

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

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

标签: javascriptflowtype

解决方案


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

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

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


推荐阅读