Rob
Rob

Reputation: 7216

How to turn a string | string[] into string[]

I'm getting a response back from nodejs that is of type string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[] but I need it to be only of type string[]. How can I do this in typescript?

The background on the issue: nodejs is returning string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[] from req.query, but I need in to be a string[] only when I'm using typeORM with a where in clause.

Here's my code so far, which does not work:

import { In } from "typeorm";    
const { investmentIds } = req.query;
const historicalReturns = await historicalReturnRepository.find({
    where: In(investmentIds)
});

Upvotes: 2

Views: 783

Answers (1)

Bastiat
Bastiat

Reputation: 797

Asserting req.query to a string[] does not change it's true type, all it does it tell TS to treat it like a string[] when doing it's type checking. As such, it can cause errors when not used with a good reason. I have definitely seen people confuse assertions with an actual practical change in object type which it is not.

if you need to ensure your processing code gets an array, then you can say something like

const { investmentIds } = req.query
const idArr = Array.isArray(investmentIds) ? investmentIds : [investmentIds];

then use idArr which we now know is an array.

Upvotes: 3

Related Questions