AIon AIon - 1 year ago 164
TypeScript Question

TypeScript complaining that 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

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[]) => {

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

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

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

Here is a snapshot:

enter image description here

Answer Source

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){
    } else { => s);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download