用 in 运算符收窄未声明的属性

版本新特性 / TypeScript 4.9

// *** before: ***
function readPackageName(context: object) {
    if ("packageJSON" in context) {
        // context.packageJSON; // <-Error: type object has no properties at all
    }
}

// *** in version 4.9: ***
function readPackageNameChecked(context: object) {
    if ("packageJSON" in context) {
        console.log(context.packageJSON); // OK: context is narrowed to {
        //packageJSON: unknown }
    }
}