#Type error with union types even after explicit check with if statement. (Recursive type definition)

5 messages · Page 1 of 1 (latest)

upper igloo
#

Code snippet to reproduce :

type Queries = Array<{
    value: string | Queries;
}>;

function processQuery(query: Queries) {
    console.log(query);
}

const temp: Queries = [{ value: [] }, { value: 'abc' }];

for (let i = 0; i < temp.length; i++)
    if (Array.isArray(temp[i].value)) {
        processQuery(temp[i].value);
    }

Here in the line processQuery(temp[i].value) I am getting the error Argument of type 'string | Queries' is not assignable to parameter of type 'Queries'.

One thing I can do is to remove the error is to write processQuery(temp[i].value as Queries). This seems a bit hacky. Is there a better way to handle this?

Thanks.

whole mango
#

yeah don't go for the assertion

#

im not quite sure why the narrowing is lost, perhaps due to the indexed access

#

but in general, unless you need to use i, using a for..of loop tends to be cleaner and also lets ts do a lot more work

craggy wolfBOT
#
that_guy977#0

Preview:```ts
type Queries = Array<{
value: string | Queries
}>

function processQuery(query: Queries) {
console.log(query)
}

const temp: Queries = [{value: []}, {value: "abc"}]

for (const query of temp)
if (Array.isArray(query.value)) {
processQuery(query.valu
...```