我遇到了以下问题:在我的应用程序中,我有一个Map
,其中一组lambda函数与大约Role
配对.每个lambda获取secondParameter
并返回settings
对象.
enum Role {
ROLE_1 = "role"
}
const settingsRole1 = {}
const defaultSettings = {}
const secondParameter = ""
const map = new Map<Role, (secondParameter: string) => any>([
[Role.ROLE_1, (secondParameter: string) => settingsRole1]
]);
const settings = map.get(Role.ROLE_1)(secondParameter) ?? defaultSettings;
I received this error while trying to calling the function returning from the map: TS2722: Cannot invoke an object which is possibly 'undefined'
.
I tried to guard it as shown below, but it doesn't seem to work...
const settings = map.has(Role.ROLE_1) ? map.get(Role.ROLE_1)(secondParameter) : defaultSettings;
如答案here所示,似乎使用optional chaining operator
就行了,所以下面的代码片段实现了一个工作警卫
const settings = map.get(Role.ROLE_1)?.(secondParameter) ?? defaultSettings;
为什么使用optional chaining operator
构建的守卫可以工作,而使用if map.has()
构建的守卫则不能?