Home > Mobile >  Typescript iterate and filter an array of different types
Typescript iterate and filter an array of different types

Time:11-22

Does anyone know how can i filter and get numbers greater than 250 in an array consisting of two different types i.e

interface Foo {
    myNumber: number
}

interface Bar {
    present: boolean
}

const myArray : (Foo | Bar)[] = [{myNumber: 200}, {myNumber:600}, {myNumber:450}, {present: true}]

myArray.filter((it: Foo|Bar) => it?.myNumber >= 250)

The error i am getting is "Property 'myNumber' does not exist on type 'Foo | Bar'."

i know the reason behind the error message however can't think of a straight forward solution atm.

playground

CodePudding user response:

I don't see why you're using two different interfaces but,
In my opinion, it can be done in one interface using optional fields.
And this is how it looks with one interface

interface Foo {
    myNumber?: number,
    present?: boolean
}

const myArray : (Foo)[] = [{myNumber: 200}, {myNumber:600}, {myNumber:450}, {present: true}]

console.log(myArray.filter((it: Foo) => it?.myNumber && it?.myNumber >= 250))

let me know if you REALLY need two interfaces I can update the answer...

CodePudding user response:

Letting TS infer the type of the array as Aluan Haddad suggested in the comments is certainly one way. However, I assume you want to keep the array typed as Foo | Bar to make sure the array doesn't contain anything else.

You can define the infered type on your own as

type FooOrBar = (Foo & {
    [Key in keyof Bar]?: never;
}) | (Bar & {
    [Key in keyof Foo]?: never;
});

And use this type for it:

myArray.filter((it: FooOrBar) => it.myNumber !== undefined && it?.myNumber > 250);

Or maybe avoid the undefined-check with

myArray.filter((it: FooOrBar) => Number(it?.myNumber) > 250);

Playground

  • Related