jam*_*slk 8 javascript flowtype
我有以下代码,它应该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];
}
}
Run Code Online (Sandbox Code Playgroud)
但相反,我收到以下错误:
10: objectWithSomeExampleKeys[example];
^ Cannot get `objectWithSomeExampleKeys[example]` because property `bar` is missing in object literal [1].
References:
3: const objectWithSomeExampleKeys = {
^ [1]
Run Code Online (Sandbox Code Playgroud)
我如何让 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];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7185 次 |
| 最近记录: |