考虑使用以下类型谓词函数来判断对象是否包含特定键:
export function objectHasKey<T extends object>(
obj: T,
key: PropertyKey,
includeKeysFromPrototype: boolean = false,
): key is keyof T {
return includeKeysFromPrototype ? key in obj : Object.prototype.hasOwnProperty.call(obj, key);
}
现在,考虑下面的伪代码来说明我的困惑:
let entry: unknown = {
someProperty: '123'
}
// (1) EXPECTED -> TS2339: Property 'someProperty' does not exist on type 'unknown'
console.log(entry.someProperty)
if (typeof entry === 'object' && objectHasKey(entry, 'someProperty')) {
// (2) UNEXPECTED -> TS2339: Property 'someProperty' does not exist on type 'object'
console.log(entry.someProperty)
}
尽管我已经使用类型谓词函数显式判断了someProperty
是entry
的键,但我不明白为什么TypeScrip会在(2)处引发错误.