我有以下代码,它应该使用 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
中的属性?
最佳答案
我找到了解决这个问题的办法:
如果我使用 {[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];
}
}
关于javascript - 流 : Cannot get . .. 因为对象文字中缺少属性 ...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54354854/