TypeScript抱怨string.[]类型数组上不存在array.map [英] TypeScript complaining that array.map is not present on array of type string[]
问题描述
我有一个带有TypeScript的Angular 2项目.我不明白为什么TypeScript实时编译器抱怨 info.map
?
I have an Angular 2 project with TypeScript. I don't understand why TypeScript live compiler is complaining about the info.map
?
错误消息:无法解析的函数或方法map()
Error message: unresolved function or method map()
当我在浏览器中运行它时, 工作正常 ,但是我不明白为什么会发生,更重要的是TypeScript如何确定/else我在这里.
When I run it in the browser, is working just fine, but I don't understand why it happens and more importantly how TypeScript determines in which if /else branch I'm in.
代码:
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.
}
}
这是快照:
推荐答案
Typescript编译器无法将lodash的函数调用识别为类型检查.您可以尝试"if(info instanceof String)",在"else"分支打字稿中可以假定"info"为数组.
Typescript compiler doesn't recognise lodash's function call as a type check. You can try "if(info instanceof String)" and in the "else" branch typescript can assume the "info" is array.
这在打字稿游乐场中对我有用:
let addInfo = (info: string|string[]) => {
if(info instanceof String){
info;
} else {
info.map(s => s);
}
}
更新
感谢@Tamas Hegedus,他们分享了有关自定义类型保护的知识.我以前从没听说过.我决定在此处引用打字稿文档中有关用户定义的报价类型防护:
Update
Thanks to @Tamas Hegedus, shared knoweledge about custom type-guards. I haven't heard about them before. I've decided to put here quotation from Typescript documentation about User-Defined Type Guards:
恰恰是TypeScript有一种叫做类型保护的东西.类型防护是一些执行运行时检查的表达式,在一定范围内保证类型.要定义类型保护,我们只需需要定义一个返回类型为类型谓词的函数:
It just so happens that TypeScript has something called a type guard. A type guard is some expression that performs a runtime check that guarantees the type in some scope. To define a type guard, we simply need to define a function whose return type is a type predicate:
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
在此示例中,
宠物是鱼是我们的类型谓词.谓词表格 parameterName是类型,其中 parameterName 必须是名称来自当前函数签名的参数.
pet is Fish is our type predicate in this example. A predicate takes the form parameterName is Type, where parameterName must be the name of a parameter from the current function signature.
这篇关于TypeScript抱怨string.[]类型数组上不存在array.map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!