Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading