richbai90
richbai90

Reputation: 5204

How to deal with a variable that may be one of several types

I have a function like this

sqlQuery(query : string | Array, database = 'swdata') : Promise {
    let rest;
    if (Array.isArray(query)) {
        rest = query.splice(1);
        query = sqlString.format(query[0], rest);
    }

    const request = new Request('data', 'sqlQuery', {database, query, formatValues: true});
    return this.connection.sendRequest(request);

}

My IDE complains that there is no method splice for a string. Is that just a quirk with my IDE, or is there a better way to write this code?

Upvotes: 2

Views: 39

Answers (1)

unional
unional

Reputation: 15589

Your IDE does not properly support TypeScript Language Service.

Array.isArray() is a Type Guard function that participates in the control flow analysis of TypeScript. That means in that block, TypeScript Language Service can determine that the type of query is of type array and you should not see the error.

For example, if your IDE is WebStorm, you need to go to setting and check using TypeScript language service. Other IDE may have similar options or plugins.

You can use VSCode to test it out. It should be working just fine.

Upvotes: 2

Related Questions