Typescript:使用函数的不同结果及其使用 typeof 运算符的代码

Typescript: different result using function and its code using typeof operator

使用此代码会产生错误:

interface something {
    [id: string]: string | something;
}
let obj: something = {
    '1': 'str',
    '2': {
        '3': 'str'
    }
}; 
function isObject(obj: any): boolean {
    return typeof obj === 'object' && obj !== null;
}

for (let key in obj) {
    const specific = obj[key];

    if (isObject(specific)) {
        for (let id in specific) {
            //         ^^^// The right-hand side of a 
            // 'for...in' statement must be of type 'any',
            // an object type or a type parameter 
        }
    }
}

然而,当使用函数代码代替它时它工作正常isObject(specific):

if (typeof specific === 'object' && specific !== null) {
// ...

为什么?我应该开始删除代码中的函数吗?

当你在函数代码中使用if语句时,if语句块中的TypeScript编译器可以从条件中理解specific的类型是object.那么为什么它有效

如果你想使用函数检查,你可以写return类似obj is object的类型。这将根据您的条件 return boolean 并告诉编译器您的 obj 是否为 object

function isObject(obj: any): obj is object {
    return typeof obj === 'object' && obj !== null;
}

有关此技术的更多信息,您可以阅读 Typescript Advanced Types