foreach循环对象可能未定义

时间:2017-12-16 00:35:13

标签: typescript

为什么ts编译器认为Object可能未定义?我在循环中抓住了更高的值。我在操场here

中有错误链接
interface Params {
    [key: string]: ParamTypes
}

type ParamTypes = string | boolean | Date | number | Params | undefined

function doSomething(params: Params) {
    const paramKeys = Object.keys(params);
    paramKeys.forEach(p => {
        if (typeof params[p] === 'undefined') {
            return;
        }
        if (Object.getPrototypeOf(params[p]) === Object.prototype) {
            doSomething(<Params>params[p]);
        } else {
            return params[p].toString(); // Error: Object is potentially undefined
        }
    })
}

修改

要查看错误,您必须在选项中启用隐式空值检查。

1 个答案:

答案 0 :(得分:3)

It's a known limitation,编译器不会记录typeof检查无限制索引访问的结果。它看起来像 was a PR to allow that但它从未合并过 - 编译速度下降太多了。

解决方法是引入中间变量:

interface Params {
    [key: string]: ParamTypes
}

type ParamTypes = string | boolean | Date | number | Params | undefined

function doSomething(params: Params) {
    const paramKeys = Object.keys(params);
    paramKeys.forEach(p => {
        const param = params[p];
        if (typeof param === 'undefined') {
            return;
        }
        if (Object.getPrototypeOf(param) === Object.prototype) {
            doSomething(<Params>param);
        } else {
            return param.toString(); // Error: Object is potentially undefined
        }
    })
}