Typescript的TypeGuard在枚举器中丢失

问题描述 投票:0回答:1

[看下面的代码,我不明白为什么filter.formatter(倒数第二行)可能不确定,因为我之前检查过它是否存在:

type Filter = {
    formatter?: {
        index: number,
        func: (value: string) => void
    }
}

const filter: Filter = {
    formatter: {
        index: 1,
        func: (v) => {
            return `Label: ${v}`
        }
    }
}

const data = [['foo', 'bar']]

if (filter.formatter) {
    data[filter.formatter.index].forEach(d => {
        filter.formatter.func(d) // <-- `formatter` is possibly undefined
    })
}

TypeScript Playground

更新1

正如注释中的@CRice提及,在for循环中不会发生。但是我仍然想知道为什么吗?

Updated TypeScript Playground

typescript
1个回答
2
投票
您可以像这样重新编写代码以更好地理解该错误。

if (filter.formatter) { const itemConsumer = (d: string) => { filter.formatter.func(d) }; data[filter.formatter.index].forEach(itemConsumer); } // both are the same const itemConsumer = (d: string) => { filter.formatter.func(d) }; if (filter.formatter) { data[filter.formatter.index].forEach(itemConsumer); }

itemConsumer中,您仅捕获了对filter的引用,但未捕获其实际值。因此,在执行filter.formatter之前,itemConsumer可能为空。

for循环不是这种情况,因为您没有为其创建新函数,因此您使用过滤器值,并且编译器可以确保不能定义filter.formatter

如果您想了解更多有关此的信息,请参阅有关JS的serie of books和专门针对scope and closure的文章

© www.soinside.com 2019 - 2024. All rights reserved.