流:无法获取...,因为对象文字中缺少属性...

时间:2019-01-24 20:30:07

标签: javascript flowtype

我有以下代码,应该使用JavaScript的example运算符来优化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不能是barobjectWithSomeExampleKeys以外的其他任何属性?

2 个答案:

答案 0 :(得分:1)

问题在于示例可以为'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];
  }
}

答案 1 :(得分:0)

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

如果我使用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