javascript - 流程:无法获取...因为对象文字中缺少属性...
问题描述
我有以下代码,它应该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
?
解决方案
我找到了解决这个问题的方法:
如果我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];
}
}
推荐阅读
- javascript - 根据 num 值渲染多个项目,只渲染一个
- python - 如何在python中删除和更改附加列表?
- eclipse - Eclipse 格式化程序只是缩进
- java - 使用 appium 运行我的测试脚本时出现 SecurtyException
- python - 如何从字典中的值中获取 key_name?
- r - 重新发布图书时关闭更新提示
- android - 如何在laravel 5.7中使用retrofit send to api从android创建护照令牌,还有比护照更好的选择来进行身份验证
- tensorflow - TensorBoard 上(正确的)ANN 偏差和权重是什么样的?
- javascript - React Native Firebase:从firebase读取数据时出错
- javascript - How can I set value to componentDidMount from another function in React?