我有以下代码,应该使用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
不能是bar
或objectWithSomeExampleKeys
以外的其他任何属性?
答案 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];
}
}