AIon AIon - 2 months ago 27
TypeScript Question

TypeScript complaining that array.map is not present on array of type string[]

I have an Angular 2 project with TypeScript. I don't understand why TypeScript live compiler is complaining about the

info.map
?


Error message: unresolved function or method map()


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.

The code:

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.
}
}


Here is a snapshot:

enter image description here

TSV TSV
Answer

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.

This works for me in the typescript playground:

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