1

这是代码的要点,您可以在此处尝试。为什么会失败?

type Stuff = {
  prop?: {[string]: string}
}

const a: Stuff = {}

const b: Stuff = {
  prop: {'key': 'value'}
}

function getKey(): string {
  return 'somekey'
}

const key: string = 'somekey'


b.prop && b.prop[key]
b.prop && b.prop[getKey()] // => fails!!

错误信息是这样的

// 19: b.prop && b.prop[getKey()] // => fails!!
                        ^ Cannot get `b.prop[getKey()]` because an indexer property is missing in undefined [1].
// References:
// 2:   prop?: {[string]: string}
//             ^ [1]
4

1 回答 1

0

这里的 FLOW 错误有点误导。

问题是这Stuff.prop是您类型中的可选参数。把它变成一个必需的参数,它按预期工作。

原因是当您将其设为可选时,它Undefined会成为 prop 的有效类型,这意味着对 prop 作为变量的任何引用都将失败。是的,即使您已经测试过它存在。

老实说,我不知道如何在 FLOW 中进行这项工作,同时让 prop 是可选的。如果有人知道怎么做,我很感兴趣。

于 2018-07-03T23:04:12.097 回答