这是代码的要点,您可以在此处尝试。为什么会失败?
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]