TypeScript抱怨array.map不存在于string []类型的数组中

时间:2016-09-30 14:21:56

标签: angular typescript webstorm typescript-typings

我有一个使用TypeScript的Angular 2项目。我不明白为什么TypeScript实时编译器抱怨info.map

  

错误消息:未解析的函数或方法映射()

当我在浏览器中运行它时, 正常工作 ,但我不明白为什么会发生这种情况,更重要的是TypeScript如何确定if / else分支我在。

代码:

let addInfo = (info: string|string[]) =>  {
        if(_.isString(info)){

            console.log('info is a string');
            infos.push(info);

        }else if(_.isArray(info)){

            console.log('info is an array');
            info.map( x => { infos.push(x) }); // here is the compiling error- map is red.
        }
 }

这是一张快照:

enter image description here

2 个答案:

答案 0 :(得分:3)

Typescript编译器不会将lodash的函数调用识别为类型检查。您可以尝试" if(info instanceof String)"在"其他"分支打字稿可以假设"信息"是数组。

这适用于我typescript playground

let addInfo = (info: string|string[]) =>  {
    if(info instanceof String){
        info;
    } else {
        info.map(s => s);
    }
 }

更新

感谢@Tamas Hegedus,分享了关于自定义防护的知识。我以前没有听说过他们。我已决定在此引用Typescript documentation关于用户定义类型警卫的引文:

  

恰好,TypeScript有一种称为类型保护的东西。   类型保护是一种执行运行时检查的表达式   在某种范围内保证类型。为了定义一个类型保护,我们简单地说   需要定义一个返回类型为类型谓词的函数:

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}
     

pet is Fish 是此示例中的类型谓词。谓词需要   表单 parameterName是Type ,其中 parameterName 必须是名称   来自当前函数签名的参数。

答案 1 :(得分:2)

简单的解决方案:

我有@types/lodash/index.d.ts文件,但我认为是旧版本。 一旦我安装了新版本 - 一切都按预期工作。

因此对于使用Angular2 CLI项目的人来说,只需运行: npm install @types/lodash:)