Home > Enterprise >  Typescript: converting an array to another array with different type
Typescript: converting an array to another array with different type

Time:09-07

I have an array of objects that corresponds to one interface, and I'm using a function that takes this kind of array and spits a different array of objects that corresponds to another interface

It can look something like this:

export const filterPagesById = (
  items: FirstInterface[],
  ids: string[],
): SecondInterface[] => items.filter((route) => ids.includes(route.id));

Typescript yells at me that type FirstInterface[] is not assignable to SecondInterface[].

The function does work properly and the array is transformed to the correct SecondInterface type. How can I "promise" Typescript that the function will indeed return the correct type?

CodePudding user response:

If you are sure that the filter condition will keep only SecondInterface[] items you can use casting:

export const filterPagesById = (
  items: FirstInterface[],
  ids: string[],
): SecondInterface[] => items.filter((route) => ids.includes(route.id)) as SecondInterface[];

CodePudding user response:

TypeScript won't have any problem with this:

interface FirstInterface {
  id: string
}

interface SecondInterface {
  id: string
}

const filterPagesById = (
  items: FirstInterface[],
  ids: string[],
): SecondInterface[] => items.filter((route) => ids.includes(route.id));

That's because it knows the two interfaces/types overlap.

There's a reason TypeScript is complaining and you should try to get to the bottom of that instead of using type assertions if you can, because type assertions aren't type safe.

Can you share the two types FirstInterface and SecondInterface?

  • Related